for (int i = 0; i < 1000; i++)
{
PrivateMessage privateMessage = new PrivateMessage()
{
id=i
};
dc.PrivateMessages.InsertOnSubmit(privateMessage);
dc.SubmitChanges();
}
此方法适合插入1000条记录吗?
有更好的方法可以做到这一点吗?
答案 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();