使用LINQ插入1000条记录

时间:2011-08-12 18:39:18

标签: linq entity-framework linq-to-sql linq-to-xml linq-to-objects

 for (int i = 0; i < 1000; i++)
 {
      PrivateMessage privateMessage = new PrivateMessage()
      {
          id=i
      };
      dc.PrivateMessages.InsertOnSubmit(privateMessage);
      dc.SubmitChanges(); 
 }

此方法适合插入1000条记录吗?

有更好的方法可以做到这一点吗?

3 个答案:

答案 0 :(得分:3)

是的 - 最好不要在循环中执行InsertOnSubmit。尝试:

List<PrivateMessage> messages = new List<PrivateMessage>();

for (int i = 0; i < 1000; i++)
{
   messages.Add(new PrivateMessage() { id=i });
}

dc.PrivateMessages.InsertAllOnSubmit(messages);
dc.SubmitChanges();

答案 1 :(得分:1)

让dc.SubmitChanges()退出循环。

for (int i = 0; i < 1000; i++)
{
           PrivateMessage privateMessage = new PrivateMessage()
            {
                id=i
            };
            dc.PrivateMessages.InsertOnSubmit(privateMessage);
}
           dc.SubmitChanges(); 

答案 2 :(得分:1)

这是另一个:

Enumerable.Range(1, 1000).ToList().ForEach(x =>             
            dc.PrivateMessages.InsertOnSubmit(new PrivateMessage(){id=x}));
dc.SubmitChanges();