这个问题已经发布了好几次了,但一直没有得到很好的答案。
基本上,当使用嵌套的 TransactionScope 时,如果抛出异常,环境事务将被中止,并且不允许数据库操作或新事务。
请注意,(对我来说)必须在内部事务上使用 TransactionScopeOption.Required,而不是 TransactionScopeOption.RequiresNew,因为我需要整个事务由最顶层事务控制。 有关详细信息,请参阅 https://stackoverflow.com/a/35952497/628661。
这个问题有解决办法吗?
编辑:Db 是 SQL Server
using (var transactionScope1 = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
{
using (var transactionScope2 = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
{
try
{
// ...
throw new(); // simulate exception
transactionScope2.Complete();
}
catch { }
}
// error: The operation is not valid for the state of the transaction
var data = await myDbContext.MyTable.FirstOrDefaultAsync();
// error: The transaction has aborted
using (var transactionScope3 = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
{
// ...
transactionScope3.Complete();
}
}
对于 SQL Server,您可以在外部作用域中控制事务的命运,但任何内部作用域都可能导致事务失败。如果任何内部作用域回滚,则外部事务无法提交。