每次交易插入100条记录

问题描述:

每个transactionScope每次只能插入100条记录吗? 我想这样做,以避免在我的应用程序超时。每次交易插入100条记录

using(var scope = new TransactionScope()) 
{ 

foreach (object x in list) 

     { 
      // doing insertOnSubmit here 
     } 

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

}

所以我想插入事务中只有100个,甚至50行只是为了避免超时。

是这样的吗?

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

当然。每50-100条记录开始一次新的交易。你确切的问题是什么?

+0

我在开始foreach迭代之前就开始了事务处理,并且我在foreach中进行了所有插入操作。 (被迭代的列表可能会有多达10000个对象或更多) 我只是不知道如何在此范围内启动新的事务。 – Hallaghan 2010-07-22 11:13:04

+0

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