简体   繁体   English

实体框架6大表批量更新

[英]Entity Framework 6 large table bulk update

I'm new to Entity Framework so I hope this is not a nonsence. 我是实体框架的新手,所以我希望这不是废话。
Basically I have a large having between 30000 and 100000 records on it. 基本上,我有一个大型文件,上面有30000至100000个记录。 Fundamentally, the interesting fields on each record are the ID and the Total which has to be calculated at application side. 从根本上讲,每个记录上有趣的字段是ID和总计,必须在应用程序端进行计算。

So I'm fetching the records, project them to a Business Logic class performing the diverse calculations and assigning the new Total to that class. 因此,我正在获取记录,将它们投影到业务逻辑类中,以执行各种计算并将新的总计分配给该类。

var validPriceVersionID = context.PriceVersion.Where(f => f.Status == "VALID").FirstOrDefault().PriceVersionID;
                var tmp = context.EndItem.Where(f => f.Total == 0).Project().To<EndItem>().ToList();
                tmp.Select(c => { c.PriceVersionID = validPriceVersionID; return c; }).ToList();

Now, I need to update the whole SQL table with the new Total based on the ID and here is where my nightmare begins. 现在,我需要根据ID使用新的总计更新整个SQL表,这就是我噩梦开始的地方。 For example, something as basic as below is taking an extraordinary amount of time 例如,以下基本内容需要花费大量时间

var idTotalPair = tmp.Select(x => new {x.EndItemID, x.Total}).ToArray(); 

I've made some researchs and found out that EF does not support bulk opperations and that it does not support TableTyped parameters for stored procedures. 我进行了一些研究,发现EF不支持批量操作,并且不支持用于存储过程的TableTyped参数。

So, what I pretend is to find best (performant) way to update all those records after each Total calculation. 因此,我假装的是在每次“总计”计算之后找到最佳的(性能)方法来更新所有这些记录。 Any help will be greatelly appreciated :) 任何帮助将不胜感激:)

Thanks in advance 提前致谢

You can use a raw command. 您可以使用原始命令。 Something like: 就像是:

   using (var context = new MyContext()) 
   { 
       context.Database.ExecuteSqlCommand( 
           "UPDATE EndItem SET Total = ... WHERE EndItemId = ..."); 
   }

The most efficient way is the @jeroenh comment. 最有效的方法是@jeroenh注释。 Making everything in a Stored Procedure instead if possible. 尽可能将所有内容存储在存储过程中。

Disclaimer : I'm the owner of Entity Framework Extensions 免责声明 :我是Entity Framework Extensions的所有者

This library is not free but allows you to perform Bulk Update and other operations for this kind of scenario: 该库不是免费的,但允许您针对这种情况执行批量更新和其他操作:

  • Bulk SaveChanges 批量保存更改
  • Bulk Insert 批量插入
  • Bulk Delete 批量删除
  • Bulk Update 批量更新
  • Bulk Merge 批量合并

Example

// Easy to use
context.BulkSaveChanges();

// Easy to customize
context.BulkSaveChanges(bulk => bulk.BatchSize = 100);

// Perform Bulk Operations
context.BulkDelete(endItems);
context.BulkInsert(endItems);
context.BulkUpdate(endItems);

// Customize Primary Key
context.BulkMerge(endItems, operation => {
   operation.ColumnPrimaryKeyExpression = 
        endItem => endItem.Code;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM