2010-07-22 114 views
3

每個transactionScope每次只能插入100條記錄嗎? 我想這樣做,以避免在我的應用程序超時。每次交易插入100條記錄

using(var scope = new TransactionScope()) 
{ 

foreach (object x in list) 

     { 
      // doing insertOnSubmit here 
     } 

context.SubmitChanges(); 
scope.Complete(); 

}

所以我想插入事務中只有100個,甚至50行只是爲了避免超時。

回答

3

是這樣的嗎?

TransactionScope scope; 
bool committed = false; 
int i = 0; 
const int batchSize = 100; // or even 50 

try 
{ 
    foreach (object x in list) 
    { 
     if (i % batchSize == 0) 
     { 
      if (scope != null) 
      { 
       scope.Commit(); 
       scope.Dispose(); 
       context.SubmitChanges(); 
      } 
      scope = new TransactionScope(); 
     } 

     // doing insertOnSubmit here 
     ++i; 
    } 

    if (scope != null) 
    { 
     scope.Commit(); 
     context.SubmitChanges(); 
    } 
} 
finally 
{ 
    if (scope != null) 
    { 
     scope.Dispose(); 
    } 
} 
+0

你的代碼中有些東西完全逃脫了我。我什麼時候改變?謝謝你的協助。 – Hallaghan 2010-07-22 11:24:12

+0

@Hallaghan:恩。不是!修正:) – MPritchard 2010-07-22 11:26:17

+0

非常感謝,這正是我所需要的!我喜歡我們如何在這個網站上學到這麼多東西! – Hallaghan 2010-07-22 11:30:09

1

當然。每50-100條記錄開始一次新的交易。你確切的問題是什麼?

+0

我在開始foreach迭代之前就開始了事務處理,並且我在foreach中進行了所有插入操作。 (被迭代的列表可能會有多達10000個對象或更多) 我只是不知道如何在此範圍內啓動新的事務。 – Hallaghan 2010-07-22 11:13:04

+0

您可以創建一個新的TransactionScope。 – codymanix 2010-07-22 11:27:36