TransactionScope和多个方法调用的多个EF上下文

时间:2013-09-10 05:16:12

标签: .net entity-framework transactions transactionscope

鉴于以下代码,方法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();   
    }
}

1 个答案:

答案 0 :(得分:0)

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

因此,第一次打开连接 - 并关闭 - 位于DoDatabaseOperation。然后,在SaveChangesMethodAnotherContext中,会打开和关闭更多连接,所有连接都在TransactionScope的范围内。最后,transScope.complete();提交所有更改。

相关问题