Does ObjectContext.Connection.BeginTransaction() use MSDTC?

十年热恋 提交于 2019-12-24 00:19:07

问题


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?


回答1:


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();
}


来源:https://stackoverflow.com/questions/6857657/does-objectcontext-connection-begintransaction-use-msdtc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!