2010-05-30 76 views
3
using (TransactionScope scope = new TransactionScope()) 
{ 
    int updatedRows1 = custPh.Update(cust.CustomerID, tempPh1, 0); 
    int updatedRows2 = custPh.Update(cust.CustomerID, tempPh2, 1); 
    int updatedRows3 = cust.Update(); 

    if (updatedRows1 > 0 && updatedRows2 > 0 && updatedRows3 > 0) 
    { 
     scope.Complete(); 
    } 
} 

上述TransactionScope代碼是否正確結構化?這是我第一次使用它,所以我試圖儘可能簡單。關於.NET中的TransactionScope的問題

+1

您正在使用它就好了。您可能需要確保根據您的要求加入/不加入環境交易。你用一個TransactionOptions參數來設置它們。 http://simpleverse.wordpress.com/2008/08/05/using-transactionscope-for-handling-transactions/ – 2010-05-30 14:01:16

+0

@Mike。你應該創建一個答案,因爲它是正確的。 – Steven 2010-05-30 14:21:14

+1

其實我覺得那篇文章可能會過時的Mike。 TransactionScope不再僅僅是DTC的包裝,而且這使得它更加可用:http://stackoverflow.com/questions/1155941/transactionscope-has-it-gotten-better – 2010-05-30 14:41:21

回答

8

鎖好,

但你在做什麼是壞的設計。 如果不是每個表都更新了行,你基本上都在進行回滾。 你永遠不會知道你的交易是完成還是失敗。這可能會使解決錯誤成爲痛苦。

如果出現問題,我寧願拋出異常。這也會導致回滾。因爲scope.Complete()永遠不會到達。

using (TransactionScope scope = new TransactionScope()) 
{ 
    int updatedRows1 = custPh.Update(cust.CustomerID, tempPh1, 0); 
    int updatedRows2 = custPh.Update(cust.CustomerID, tempPh2, 1); 
    int updatedRows3 = cust.Update(); 

    if (updatedRows1 == 0 || updatedRows2 == 0 || updatedRows3 == 0) 
     throw new Exception("Not all rows could be updated"); 

    scope.Complete(); 
} 
+0

+1關於使用異常的觀點! – 2010-05-30 14:31:36

+0

太棒了................. – peace 2010-05-31 12:15:39