this code gives me th开发者_高级运维e error: the Transaction has aborted. if I remove 1 nested transaction than it doesn't throw
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" });
}
}
}
What statement does throw the error? I'd assume it is the last repo.Insert
.
Since you don't call scope.Complete(), the transaction is rollbacked (aborted) when aaa is disposed.
Generally, transaction rollback is considered an error, so all higher-level transactions also become uncommittable (or are immediately rollbacked).
So, for the last repo.Insert
there is no valid transaction to use - that's why it throws an exception.
You might need to specify the TransactionScopeOption like in this example from 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: http://msdn.microsoft.com/en-us/library/ms172152.aspx
yes, it will work. You`ve forgotten to include scope.Complete(); at the end
精彩评论