Does ObjectContext.Connection.BeginTransaction() use MSDTC?
Asked Answered
E

1

3

I want confirm if the Transaction that Entity Framework's ObjectContext.Connection.BeginTransaction() method returns uses the support of MSDTC (Microsoft Distributed Transaction Coordinator) or not?

Is there any way to use transactions without support of MSDTC?

Exuberant answered 28/7, 2011 at 10:42 Comment(1)
ObjectContext.Connection is a normal ADO.NET connection, so it's not related to Entity Framework...Buddie
M
5

It will automatically promote to a transaction coordinated by MSDTC under certain conditions. Each time you call ObjectContext.SaveChanges() a new transaction is created if there isn't already one in scope (if there is already an active transaction in scope, it will enlist in that transaction). However, by default, the connection will also be opened and closed each time you call ObjectContext.SaveChanges(). So if you're calling ObjectContext.Connection.BeginTransaction() at the beginning of a method, then calling ObjectContext.SaveChanges() multiple times while holding onto the original transaction, with some versions of SQL Server and Entity Framework, this can cause the transaction to get promoted to MSDTC because it's now using different connections within a single transaction. If you're trying to avoid your transaction getting promoted to MSDTC, then explicitly open your connection at the beginning and close it when you're done:

using(MyEntities context = new MyEntities())
using(DbConnection conn = context.Connection)
{
    conn.Open();
    DbTransaction transaction = conn.BeginTransaction();

    // now do stuff within the transaction scope

    transaction.Commit();
}

However, it's recommended that you use a TransactionScope, as it's more flexible, less platform-dependent, and will make it easier on you if in the future you decide you do actually need to something that requires MSDTC. EntityFramework will automatically enlist in the transaction if there's an active TransactionScope:

using(TransactionScope transaction = new TransactionScope())
using(MyEntities context = new MyEntities())
using(DbConnection conn = context.Connection)
{
    conn.Open();

    // now do stuff within the transaction scope

    transaction.Complete();
}
Mindexpanding answered 28/7, 2011 at 14:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.