一次更新多条记录 - EF + 存储库

update multiple record at a time - EF + repository

我的代码 -

public void SaveTagOrder(List<KeyValuePair<int, int>> result) {
        foreach(var item in result){
      var entity = _vpsdbContext.Tags.FirstOrDefault(e => e.TagId == item.Key);
            if (entity != null) { entity.SortOrder = item.Value; }
        }
        _vpsdbContext.SaveChanges();
    }

我只想一次更新多条记录。据我所知,我写了这段代码,但它是一一添加的。请告诉我另一种一次更新多条记录的方法。

技术上没有问题。 EntityFramework 更新是这样的..

您可以进行一些更改以加快该过程

选项 1

AutoDetectChangesEnabled 设置为 False Please check this answer

 db.Tags
       .Where(x=>result.Contains(x.tagId))
       .ToList()
       .ForEach(a=>a.SortOrder = value);

 db.SaveChanges();

选项 2

可以试试EntityFramework插件批量操作吧here

此处是文档后面性能部分的一小段摘录。

Batch iteration with 25000 entities
Insert entities: 880ms
Update all entities with a: 189ms
Bulk update all with a random read: 153ms
delete all entities with a: 17ms
delete all entities: 282ms

Standard iteration with 25000 entities
Insert entities: 8599ms
Update all entities with a: 360ms
Update all with a random read: 5779ms
delete all entities with a: 254ms
delete all entities: 5634ms