views:

58

answers:

3

this code gives me the 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" });
            }
        }
    }
+1  A: 

yes, it will work. You`ve forgotten to include scope.Complete(); at the end

@user281180 I did that on purpose, I don't want it to commit, and it throws me an error
Omu
+1  A: 

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

Xavier
+3  A: 

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.

VladV