【问题标题】:Detecting LINQ Inserts Before submitChanges and using BulkInsert Instead在 submitChanges 之前检测 LINQ 插入并改用 BulkInsert
【发布时间】: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


    【解决方案1】:

    好的,我找到了问题的答案。你可以从这里下载一个甜蜜的课程:

    http://code.msdn.microsoft.com/LinqEntityDataReader

    这个类非常适合我,我可以将 LINQ 生成的“客户”对象的集合传递给 SQLBulkCopy!

    【讨论】:

      【解决方案2】:

      与其做所有这些,不如直接插入 db.SubmitChanges();在每个单独的项目之后调用,还是在 X 项目块之后调用?这也不理想,但比一次性提交大量更改要好,而且可能很容易在代码中进行更改。

      为 DataContext 提供中等大小的更新,实际上并没有为您完成这些工作做得不好。然后继续做更​​有成效的事情。

      【讨论】:

      • 我不想走这条路有几个原因: 1. 用于填充 LINQ db 对象的代码分布在多个区域,并且太分散而无法开始到处修改。我需要能够对完全填充的 db 对象进行操作。 2.相对于我引用的帖子,我仍然认为性能很差。我想利用那个帖子,因为那里的插入速度非常快。 db.SubmitChanges() 是每一行的单独插入。
      • 好吧,如果您无法对代码进行重大更改,那么您也几乎无能为力。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多