简体   繁体   English

实体框架多行更新

[英]Entity framework multiple row update

I was wondering if there is a smarter/faster/one_line way to approach this. 我想知道是否有更聪明/更快/更简单的方法来解决这个问题。

I have a list of dll's with IsActive property. 我有一个具有IsActive属性的dll列表。 On the UI I have checkboxes which change state of dll's depending on whether the checkbox is checked or not. 在UI上,我有多个复选框,这些复选框根据是否选中了dll来更改dll的状态。 Change happens on button click. 单击按钮即可更改。 I have no problem traversing the whole DB so now I am doing it like this: 我遍历整个数据库没有问题,所以现在我这样做:

foreach (var item in dllList)
{
    context.dllSet.Find(item.Id).IsActive = item.IsActive;
}

( dllList is List<> element connected to WPF front). dllList是连接到WPF前端的List<>元素)。

So now I am finding element with same id in DB, and changing its state to one that is in presented in UI checkbox. 所以现在我在数据库中找到具有相同ID的元素,并将其状态更改为UI复选框中显示的元素。

Solution I'd like would be something like this: 解决方案我想要的是这样的:

context.dllSet.AddOrUpdateList(dllList);

Create Stored procedure with Datatabel as a parameter and implement the logic in DB end. 使用Datatabel作为参数创建存储过程 ,并在DB端实现逻辑。

Call your stored procedure from entity framework. 从实体框架调用您的存储过程。

The fastest way is using a library supporting Batch Update 最快的方法是使用支持批量更新的库

See: Entity Framework Batch Update Library 请参阅: 实体框架批处理更新库

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

Example

var idsTrue = list.Where(x => x.IsActive).Select(x => x.Id).ToList();
var idsFalse = list.Where(x => !x.IsActive).Select(x => x.Id).ToList();

ctx.dllSet.Where(x => idsTrue.Contains(x.Id)).Update(x => new Dll() {IsActive = true});
ctx.dllSet.Where(x => idsFalse.Contains(x.Id)).Update(x => new Dll() {IsActive = false});

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

Another way is using bulk operations and modifying only the IsActive column 另一种方法是使用批量操作并仅修改IsActive列

// Update all columns
ctx.BulkUpdate(list);

// Update only IsActive column
ctx.BulkUpdate(new List<Dll>(), operation => operation.ColumnInputExpression = dll => new { dll.Id, dll.IsActive});

// Add new entities, update existing entities
ctx.BulkMerge(list);

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

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