entity-framework-6 - 在 EF6 中进行批量更新的更优雅的方式
问题描述
这是在 WPF 应用程序中。
目前我有以下代码可以工作,但速度很慢:
public void IgnoreOffers(ICollection<Offer> offers)
{
using (var context = new DbContext())
{
foreach (Offer o in offers)
{
var offer = context.Offers.Find(o.Id);
offer.Ignore = true;
}
context.SaveChanges();
}
}
我知道所有的报价都已经存在于数据库中
有没有更高效的方法来做到这一点?
解决方案
免责声明:我是Entity Framework Plus项目的所有者
该库允许您执行BatchUpdate
context.Offers.Where(o => offers.Contains(o.Id)
.BatchUpdate(o => new Offer() { Ignore = true });
如果您的报价太多,您可能需要分批进行,因为 SQL 中的参数数量是有限的。
一切都将在数据库端完成,因此不需要在应用程序端加载任何报价。
此方法将为您提供最佳性能。
免责声明:我是实体框架扩展项目的所有者
该库不是免费的,但提供了这些BulkUpdate
功能。
// BulkUpdate
context.BulkUpdate(offers);
// If you want to only update the `Ignore` property
context.BulkUpdate(offers, o => o.ColumnInputExpression = x => new { x.Ignore });
推荐阅读
- python - 如何跳过特定模块中的所有测试用例?
- java - 通过Java中的方法传递变量
- android - 向上或向下滚动后,项目在 recyclerView 中放错位置
- c# - 使用包含条件的 C# 中的方法映射对象的正确方法
- linux - 如何在 centos 7 上重新加载 pythonic 服务?
- java - 生产者消费者代码问题(似乎通知方法没有释放循环内的锁)
- mongodb - $filter 在 mongodb 中最多 2 个嵌套级别
- powershell - 获取由 PowerShell 创建的现有 Internet Explorer 窗口
- rust - 计算获取块的平均值时出错
- python - 打印python文件中每个字符的统计信息