[英]insert list of objects with linq-to-sql
I have a list of objects that I'm inserting in a database with linq-to-sql. 我有一个对象列表,我正在使用linq-to-sql插入数据库。 At the moment, I'm using a foreach loop that adds each element and that looks roughly like this: 目前,我正在使用foreach循环添加每个元素,看起来大致如下:
foreach (o in List<MyObjectModel)
{
using MyDataContext
{
TheLinqToSqlTableModel TheTable = new TheLinqToSqlTableModel();
TheTable.Fieldname = o.Fieldname;
.... repeat for each field
MyDataContext.TheTablename.InsertOnSubmit(TheTable);
MyDataContext.SubmitChanges();
}
}
Is there a better way to insert a list of objects in a DB using linq-to-sql? 有没有更好的方法使用linq-to-sql在数据库中插入对象列表?
Thanks for your suggestions. 谢谢你的建议。
Why don't you use InsertAllOnSubmit() method. 为什么不使用InsertAllOnSubmit()方法。
Example: 例:
IEnumerable<Post> _post = getAllNewPost();
Using(Datacontext dc = new Datacontext())
{
dc.Posts.InsertAllOnSubmit(_post);
dc.SubmitChanges();
}
That's all you need. 这就是你所需要的。
//////////////////////// ////////////////////////
Some quick improvements to consider.. 一些快速改进要考虑..
a) Why creating datacontext for each iteration? a)为什么要为每次迭代创建datacontext?
Using(Datacontext dc = new Datacontext())
{
foreach(...)
{
}
dc.SubmitChanges();
}
b) Creating a stored procedure for the Insert and using it will be good for performance. b)为Insert创建存储过程并使用它将有利于提高性能。
c) Using Transaction Scope to undo insertions if any error encountered. c)如果遇到任何错误,使用事务范围撤消插入。
Using (TransactionScope ts = new TransactionScope())
{
dc.SubmitChanges();
}
List<Object> Obj = (Enter the List you want to pass)
foreach (var item in Obj)
{
item.Get your desired value after the dot
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.