加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 实体框架中多个上下文的单个事务6

发布时间:2020-12-15 06:57:17 所属栏目:百科 来源:网络整理
导读:我们有一个方案来在单个事务中从两个上下文中保存两个实体. 步骤1 – SetTransaction(firstContext,true); 步骤2 – 使用firstContext保存第一个实体. 步骤3 – SetTransaction(secondContext,false); 步骤4 – 使用secondContext保存第二个实体 步骤5 – 最
我们有一个方案来在单个事务中从两个上下文中保存两个实体.

步骤1 – SetTransaction(firstContext,true);

步骤2 – 使用firstContext保存第一个实体.

步骤3 – SetTransaction(secondContext,false);

步骤4 – 使用secondContext保存第二个实体

步骤5 – 最后提交交易.

void function SetTransaction(context,startNewTransaction)
{    
   var currentContext = firstContext;

   if (startNewTransaction)
   {
      var connection = currentContext.GetConnection();
      connection.Open();
      this.dbTransaction = connection.BeginTransaction();
   }

   if (this.dbTransaction != null)
   {
       currentContext.UseTransaction(dbTransaction);
   }
}

当执行步骤3,currentContext.UseTransaction(dbTransaction);行将异常抛出为“传入的事务不与当前连接相关联,只能使用与当前连接关联的事务”

请建议如何解决.

Venkat.

解决方法

使用TransactionScope. EF将自动加入正在运行的事务范围.

它将要求您的连接字符串相同.

using (var scope = new TransactionScope()) {
    // Save entity in context A
    using (var contextA = new ContextA()) {
        contextA.Save(...);
        contextA.SaveChanges;
    }
    // Save entity in context B
    using (var contextB = new ContextB()) {
        contextB.Save(...);
        contextB.SaveChanges;
    }
    // Commit tx-scope
    scope.Complete();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读