除了一些更新/删除之外,我还有一堆代码可以将10k到20k的插入添加到LINQ。所有这些更改都是通过db.SubmitChanges()调用提交的。问题是太慢了:(在StackOverflow上的这篇伟大文章中对性能进行了彻底的测试:
Very slow insert process using Linq to Sql
问题是,我不想重写准备我的DB对象的所有代码。我试图在下面编写我想做的代码。
免责声明:这不是真正的代码!它不会编译..。甚至不接近:)
旧方式:
SchedDB.Data.SchedulerDBDataContext db = new SchedDB.Data.SchedulerDBDataContext();
//Do a bunch of stuff to populate "db"
db.SubmitChanges()新途径:
SchedDB.Data.SchedulerDBDataContext db = new SchedDB.Data.SchedulerDBDataContext();
//Do a bunch of stuff to populate "db"
//NEW: Detect all of the inserts in the "db" object. Remove those inserts and generate code to insert them with a batch dataadapter. For example:
//
//DataTable dtProducts = new DataTable()
//dtProducts.Columns.Add(ProductID) //yada yada all of the columns here
//
//DataTable dtCustomers = new DataTable()
//dtCustomers.Columns.Add(CustomerID) //yada yada all of the columns here
//foreach (insertItem in db.Inserts) //this is pseudo code, I need help here
//{
// if (insertItem.destinationTable == "Products")
// {
// DataRow dr = dtProducts.NewRow();
// dr["ProductID"] = insertItem.ProductID; //This line of code probably isn't even close to being right... I can't imagine the "insertItem" holding all of the columns no matter what the destinationTable is
// }
// if (insertItem.destinationTable == "Customers")
// {
// //similar code, all customer columns, yada yada
// }
// IMPORTANT: remove the item from the LINQ db so it doesn't insert it anymore
//
// Make a table adapter for each datatable
// Set the .BatchSize parameter
//Commit each table adapter.
// db.SubmitChanges() //If there are any updates or deletes they are still in here and still need to happen.如果在大量更新中有任何错误,那么很高兴知道这一点,这样我就可以回滚LINQ,并可能运行一些其他代码来清除dataapapters插入。(我可以处理这个问题,我的所有插入都有一个额外的列,它是批处理插入所特有的int。)
发布于 2010-11-06 00:00:38
好的,我找到了我问题的答案。你可以从这里下载一堂甜蜜的课:
http://code.msdn.microsoft.com/LinqEntityDataReader
这个类非常适合我,我可以传递一个由LINQ生成的“客户”对象的集合!
发布于 2010-11-01 18:49:11
为什么不直接插入db.SubmitChanges();在每一项之后调用,或者在X项块之后调用?这也不太理想,但比一次性提交大量更改要好,而且可能很容易在代码中更改。
为DataContext提供中等大小的更新,实际上它在为您完成这些更新方面做得并不糟糕。然后继续做更有成效的事情。
https://stackoverflow.com/questions/4072010
复制相似问题