2010-10-05 117 views
8

此代码给我错误:交易已中止。 如果我删除1个嵌套事务比不投2同胞嵌套transactionScope给出:交易已中止

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" }); 
      } 
     } 
    } 

回答

12

什么语句也抛出这个错误吗?我认为这是最后的repo.Insert

由于您没有调用scope.Complete(),因此在处理aaa时事务会回滚(中止)。
通常,事务回滚被视为错误,因此所有更高级别的事务也变为不可提交(或立即回滚)。
因此,最后的repo.Insert没有有效的事务要使用 - 这就是为什么它会抛出异常。

2

是的,它会工作。你已经忘记包含scope.Complete();在结束

+0

@ user281180我这样做的目的,我不希望它提交,它会抛出一个错误 – Omu 2010-10-05 06:42:55

3

您可能需要从MSDN在这个例子中,指定像TransactionScopeOption:

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)) 
    { 
    ... 
    } 
} 

编号:http://msdn.microsoft.com/en-us/library/ms172152.aspx