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中實現事物提交
在_unitOfWorkManager中獲取的一個Dbcontext,
var strategy = _unitOfWorkManager.Current.GetDbContext<TestDBContext>().Database.CreateExecutionStrategy();
strategy.Execute(() =>
{
using (var transaction = new TransactionScope())
{
_unitOfWorkManager.Current.SaveChanges();
transaction.Complete();
}
});
使用策略事物