EF Core – ExecuteUpdate and ExecuteDelete (Bulk updates 批量更新和删除)

前言

EF Core 在 SaveChanges 之后会一句一句的去更新和删除数据. 有时候这个效率是很差的. 

而 SQL 本来就支持批量更新和删除, 所以是 EF Core 的缺失. 在 EF Core 7.0 它补上了这个功能.

 

ExecuteDelete

await db.Customers.Where(e => e.Name.Length > 1).ExecuteDeleteAsync();

语法很简单, filter 出要删除的数据, 然后执行 ExecuteDeleteAsync, 它是直接执行的, 不需要 SaveChanges

SQL Query

当遇到 Owned Entity 有 Error

不知道是不是 Bug. 等过了 RC 版本再试试呗

.ExecuteDelete()' could not be translated. Additional information: The operation 'ExecuteDelete' requires an entity type which corresponds to the database table to be modified. The current operation is being applied on a non-entity projection.

 

ExecuteUpdate

await db.Customers
    .Where(e => e.Name == "Derrick")
    .ExecuteUpdateAsync(s => 
        s.SetProperty(e => e.Name, e => "prefix" + e.Name)
        .SetProperty(e => e.Age, e => e.Age + 1)
    );

首先是 filter 出要 update 的 data. 然后调用 ExecuteUpdateAsync, 指定更新的 column 和最终的值, 要同时 update 多个 column 就多次调用 SetProperty.

设置值的时候还可以依赖其它 column value 哦.

SQL Query

当遇到 Owned Entity 也是会有 Error 哦.

 

posted @ 2022-09-26 16:46  兴杰  阅读(1355)  评论(0编辑  收藏  举报