ABP-多个DbContext实现事物更新

1.在ABP中其实多个DbContext并没有在同一个事物中执行,那他是如何操作的,我的理解是

  • 在不使用事物的时候
    把多个DbContext存放在ActiveDbContexts 在调用工作单元的时候。savechange方法会循环这个List
public override void SaveChanges()
        {
            foreach (var dbContext in GetAllActiveDbContexts())
            {
                SaveChangesInDbContext(dbContext);
            }
        }

   protected virtual void SaveChangesInDbContext(DbContext dbContext)
        {
            dbContext.SaveChanges();
        }
  • 使用事物的时候
var  ActiveTransactions = new Dictionary<string, ActiveTransactionInfo>();

然后循环这个 ,一个个commit

 public void Commit()
        {
            foreach (var activeTransaction in ActiveTransactions.Values)
            {
                activeTransaction.DbContextTransaction.Commit();

                foreach (var dbContext in activeTransaction.AttendedDbContexts)
                {
                    if (dbContext.HasRelationalTransactionManager())
                    {
                        continue; //Relational databases use the shared transaction
                    }

                    dbContext.Database.CommitTransaction();
                }
            }
        }

所有不同数据库的事物 没有在一个事物中实现。

2.如何实现在多个DbContext中实现事物提交

官方文档1
官方文档2

在_unitOfWorkManager中获取的一个Dbcontext,

 var strategy = _unitOfWorkManager.Current.GetDbContext<TestDBContext>().Database.CreateExecutionStrategy();
  strategy.Execute(() =>
            {
                using (var transaction = new TransactionScope())
                {
                    _unitOfWorkManager.Current.SaveChanges();

                    transaction.Complete();
                }
            });

使用策略事物

原文地址:https://www.cnblogs.com/gudanshiyigerendekuanghuan/p/11194537.html