2011-02-28 51 views
8

我是C#中的新手。所以我只是想知道是否有人能幫我弄清楚C#如何與transactionscope配合使用?因爲我對它的定義有點困惑。但是,讓我稍微解釋一下我的問題。這樣你就會知道我在努力達到什麼目的。.NET Transactionscope選項

我已經宣佈了三個不同的數據集這樣的三個表適配器:

logTableAdapter logAdap = new logTableAdapter(); 
measTableAdapter measAdap = new measTableAdapter(); 
valueTableAdapter valueAdap = new valueTableAdapter(); 

導入數據的過程是:

  1. 首先,我通過插入一個logAdap.insert日誌條目()方法。
  2. 通過excel文件循環抓取測量結果並開始通過measAdap.insert()方法插入。
  3. Foreach測量我通過valueAdap.insert()方法插入值。

所以我的問題是 - 因爲測量&值具有嵌套關係。如何在任何地方發生錯誤(測量插入/值插入)時我如何創建一個嵌套事務處理器&我只想回滾我所做的一切。這是我只想回到我插入日誌條目之前的點。

+0

順便說一句,沒有「C#.NET」這樣的東西。這只是「C#」。 –

回答

0

你不需要多個TransactionScope,你可以做同樣的事情,我認爲。

+0

所以你認爲僞邏輯是這樣的: '使用code' (TransactionScope的TS =新的TransactionScope()){ \t嘗試 \t { \t \t的foreach(.....) { \t \t \t measAdap.InsertMeas(.....); \t \t \t的foreach(.....) \t \t \t { \t \t \t valAdap.InsertVal(.....); \t \t \t} \t \t} \t \t \t measAdap.Commit(); \t valAdap.Commit(); } catch(Exception ex) { measAdap.Rollback(); valAdap.Rollback(); \t} } 'code' – Mystic

+0

@Mystic使用該邏輯,事務被提升爲使用分佈式事務協調器。這個SO回答告訴你爲什麼你可能不希望這樣:http://bit.ly/gGampm - 請參閱我的解決方法。 – jevakallio

2

引用此適當命名的文章:The definitive TableAdapters + Transactions blog post

如果您正在使用多個操作工作的一個TransactionScope的內部,即「的GetData」和「更新」兩個單一的TransactionScope內,或兩個更新的一個TransactionScope中,你將有效打開兩個SqlConnections到單個數據庫,並從而不必要地促進了從LTM到MSDTC的交易。作爲最佳實踐,始終只在TransactionScope中包裝單個操作。如果您選擇在單個TransactionScope中包裝多個操作,那麼您必須通過擴展部分類定義來自己管理連接生命週期。換句話說,下面的代碼將導致交易推動 -

using (TransactionScope tsc = new TransactionScope()) 
{ 
    tableAdap.GetData() ; 
    //Do your transactional work. 
    tableAdap.Update() ; 
    tsc.Complete() ; 
} 

但下面的代碼就好了 -

using (TransactionScope tsc = new TransactionScope()) 
{ 

    tableAdap.OpenConnection() ; 
    tableAdap.GetData() ; 

    //Do your transactional work. 
    tableAdap.Update() ; 
    tableAdap.CloseConnection() ; 
    tsc.Complete() ; 
} 

所以,你只需要一個TransactionScope,但有一些注意事項。這是主旨,但我鼓勵你閱讀博客文章。

TableAdapters不是高完整性事務處理系統的最合適的數據訪問方法。如果你需要更多的可靠性,你應該把你的操作寫成一個存儲過程,並從你的C#代碼中執行它。

0

正如我認爲,你要找的是如何使用TransactonScope,這裏是你的代碼將是什麼樣子,修改一點點在您的評論的例子:

using(TransactionScope ts = new TransactionScope()) { 
    try 
    { 
     logAdap.InsertLog(.....); 

     foreach (.....) 
     { 
      measAdap.InsertMeas(.....); 
      foreach (.....) 
      { 
       valAdap.InsertVal(.....); 
      } 
     } 

     // Complete the transaction 
     ts.Complete(); 
    } 
    catch (Exception ex) 
    { 
     // Your error handling here. 
     // No need to rollback each table adapter. That along with all the 
     // transaction is done for you when exiting the using block without 
     // calling Complete() on the TransactionScope. 
    }} 

使用這種方法該範圍稱爲隱式事務,您可以在此MSDN文章中獲得關於該範圍的完整概述:Implementing an Implicit Transaction using Transaction Scope

話雖如此,fencliff提到的是真實的,因爲您可能不想爲您的場景打開多個連接,節省寶貴的數據庫資源。