2010-10-05 54 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