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();
                }
            });

使用策略事物


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM