【发布时间】:2010-11-06 08:00:38
【问题描述】:
除了一些更新/删除之外,我还有一堆代码被设置为向 LINQ DB 添加 10k 到 20k 插入。所有这些更改都是通过 db.SubmitChanges() 调用提交的。问题是它太慢了:(性能已经在 StackOverflow 上的这篇很棒的帖子中进行了全面测试:
Very slow insert process using Linq to Sql
问题是我不想重写所有准备我的数据库对象的代码。我试图在下面编写我想做的代码。
免责声明:这不是真正的代码!它不会编译....甚至不会关闭:)
旧方式:
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 db 并可能运行一些其他代码来清除 dataapapters 插入。 (我可以处理这个问题,我所有的插入都有一个额外的列,它是批量插入所独有的 int。)
【问题讨论】:
标签: sql linq linq-to-sql bulkinsert