c# - TransactionScope 是否适用于不同的 Context 对象

标签 c# asp.net asp.net-mvc entity-framework

我在 BLL 中使用 TransactionScope。我在数据访问层上有存储库类,它为每个 crud 创建自己的 Context。这行得通吗?

在比尔:

using (var scope = new TransactionScope(TransactionScopeOption.Required)) 
    { 
        rep.addItme(Myentity);
        rep.updateItme(MyAnotherEntity);
            scope.Complete(); 
    }

在数据访问中:

class rep
{
  void addItmem(Entity entity)
  {
    using(var context=new MydbContext)
     {  
     //---state is set here
     context.Entity.add(entity);
     context.SaveChanges();
    }

   }
  void updateItem(Entity entity)
 {
 using(var context=new MydbContext)
   {
     //--state is set here
     context.Entity.add(entity);
      context.SaveChanges();
  }
}

最佳答案

在 TransactionScope 的范围(括号)内实例化的所有 DbContext 将自动注册到 TransactionScope 的内部事务中,默认情况下它是 Ambient 事务。所以是的,它应该有效。

关于c# - TransactionScope 是否适用于不同的 Context 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36527090/

相关文章:

Android 与 ASP.NET MVC4 的连接

c# - asp.net mvc 区域和主站点具有/相同的 Controller 名称

c# - 使用反射的实际方法签名

c# - ASP.NET MVC登录客户端/ASP.NET WebAPI认证/授权服务器分离

javascript - 使用 javascript 函数打开选项卡

jquery - 如何将错误消息显示回 ASP.NET MVC 页面?

c# - 如何重构程序代码?

C# Excel 单元格内容部分删除

c# - TransactionInterop.GetDtcTransaction() 抛出 ArgumentNullException ... 有时

c# - OleDbCommand 中的参数未更改