C# 2同级嵌套transactionScope给出:事务已中止
此代码告诉我错误:事务已中止。 如果我删除1个嵌套事务,它不会抛出C# 2同级嵌套transactionScope给出:事务已中止,c#,.net,ado.net,transactionscope,C#,.net,Ado.net,Transactionscope,此代码告诉我错误:事务已中止。 如果我删除1个嵌套事务,它不会抛出 using(var scope = new TransactionScope()) { repo.Insert(new Foo {Fname = "aaaa"}); using(var s = new TransactionScope()) { repo.Insert(new Foo { Fname = "aaaa" });
using(var scope = new TransactionScope())
{
repo.Insert(new Foo {Fname = "aaaa"});
using(var s = new TransactionScope())
{
repo.Insert(new Foo { Fname = "aaaa" });
//if I remove this transaction it is not going to throw exception
using (var aaa = new TransactionScope())
{
repo.Insert(new Foo { Fname = "aaaa" });
}
using(var ssa = new TransactionScope())
{
repo.Insert(new Foo { Fname = "aaaa" });
}
}
}
是的,它会起作用的。您忘了包括scope.Complete();最后,您可能需要指定TransactionScope选项,如MSDN中的示例所示:
using(TransactionScope scope1 = new TransactionScope())
//Default is Required
{
using(TransactionScope scope2 = new
TransactionScope(TransactionScopeOption.Required))
{
...
}
using(TransactionScope scope3 = new TransactionScope(TransactionScopeOption.RequiresNew))
{
...
}
using(TransactionScope scope4 = new
TransactionScope(TransactionScopeOption.Suppress))
{
...
}
}
Ref:什么语句抛出错误?我假设这是最后一次
回购。插入
由于您不调用scope.Complete(),因此在处理aaa时事务将回滚(中止)。
通常,事务回滚被认为是一个错误,因此所有更高级别的事务也会变得不可提交(或立即回滚)。
因此,对于最后一个repo.Insert
没有有效的事务可使用-这就是它引发异常的原因。@user281180我故意这么做,我不想让它提交,它引发了一个错误