executeupdate仅支持根实体标量属性更新,不支持导航属性;executedelete绕过跟踪器且不触发生命周期钩子;二者性能依赖where条件是否命中索引。
ExecuteUpdate不支持复杂导航属性更新
EF Core 7+ 引入的 ExecuteUpdate 是服务器端批量更新,但只作用于查询根实体的**直接映射字段**,无法更新关联表或导航属性。比如你写 ctx.Orders.Where(x => x.Status == "Pending").ExecuteUpdate(x => new Order { UpdatedAt = DateTime.UtcNow }) 是合法的;但写成 new Order { Customer.Name = "NewName" } 会编译失败——EF 不解析导航路径赋值,底层 SQL 也不支持跨表 UPDATE(除非手写 JOIN)。
常见错误现象:System.InvalidOperationException: The property 'Customer.Name' is not part of the entity type 'Order'。
- 只更新当前 DbSet 对应实体的标量属性(
string、int、DateTime等) - 支持简单表达式:如
x => new Order { Total = x.Total * 1.1 },但不能调用方法(ToUpper())、不能访问子对象 - 若需更新关联数据,必须拆成独立语句,或改用原始 SQL +
FromSqlRaw
ExecuteDelete执行前必须确保无跟踪实体冲突
ExecuteDelete 同样是服务端批量删除,绕过 Change Tracker,因此不会触发 EntityEntry.State 变更或 SaveChanges 时的级联逻辑。如果上下文里已有被匹配到的实体处于 Added 或 Modified 状态,EF Core 会在执行时抛出异常:InvalidOperationException: The instance of entity type 'Product' cannot be tracked because another instance with the same key value is already being tracked.