【问题标题】:TransactionScope and multiple EF contexts across multiple method calls跨多个方法调用的 TransactionScope 和多个 EF 上下文
【发布时间】:2013-09-10 05:16:12
【问题描述】:

给定以下代码,DoDatabaseOperation()MethodAnotherContext() 方法会包含在事务中吗?请注意,context1context2 的类型相同,并且正在处理连接字符串。

using (EFContext context1 = new EFContext())
{
  using (TransactionScope transScope = new TransactionScope())
  {
          DoDatabaseOperation(context1);  // Call context1.functionImport to update records
          while (....) 
          {
              .................A lot of code............
              context1.SaveChanges();              
              MethodAnotherContext();          
          }
          transScope.complete();
   }
}

public void MethodAnotherContext()
    using (EFContext context2 = new EFContext())
    {
        ......................
        context2.SaveChanges();   
    }
}

【问题讨论】:

    标签: .net entity-framework transactions transactionscope


    【解决方案1】:

    TransactionScope 的生命周期内打开的相同连接字符串上的连接将被列入同一个“简单”事务(“简单”意味着:不需要分布式事务协调器)。默认情况下,EF 上下文仅在实际需要数据库交互时打开连接,然后关闭它们。它们在创建时不会打开连接。

    所以第一次打开和关闭连接是在DoDatabaseOperation。然后,在SaveChangesMethodAnotherContext 中,更多的连接被打开和关闭,都在TransactionScope 的范围内。最后,transScope.complete(); 提交所有更改。

    【讨论】:

    • 请确认我理解您的回答,您说“是”,如果这些方法正在访问同一个数据库(相同的连接字符串),那么它们都将在同一个事务中。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    相关资源
    最近更新 更多