首页 > 解决方案 > 在 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-6crud

解决方案


免责声明:我是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 });

推荐阅读