
You Don't Have to Load Entities to Update Them: ExecuteUpdate and ExecuteDelete
- كاتب موثّق
- EF Core 10
محتويات المقال
IsActive to false in a loop and calls SaveChanges. In staging it matched a few hundred rows and finished instantly. Then a data migration brought in a decade of old accounts, and the job started taking minutes and pushing the worker's memory up every night. The SQL log shows why: one SELECT that returns every column of every match, followed by hundreds of batched UPDATE commands, each changing one row.
The common misconception
SaveChanges. Anything else means dropping down to raw SQL.
SaveChanges batches its statements into a few round trips. And it really is the right tool when you're editing a handful of entities that a user loaded into a form.
What actually happens
SaveChanges needs every row in memory first
UPDATE per changed row. Batching groups those statements into fewer round trips, up to 42 per batch on SQL Server by default, but the database still runs each one separately.
SELECT and 953 batches. It allocated about 310 MB and took between 1.4 and 2.3 seconds on a local database. On SQLite, which sent each UPDATE as its own command, the same job took 40,001 commands.
ExecuteUpdate is a query that ends in UPDATE
ExecuteUpdate uses the same LINQ you'd use to query the rows, then sets columns with SetProperty, either to a value or to an expression over the current one, such as p => p.Stock - 1. EF Core translates the whole thing into a single UPDATE ... WHERE and returns the number of rows affected. ExecuteDelete does the same with DELETE. Global query filters still apply: in the test, a soft-delete filter kept the update away from deleted rows.
ExecuteUpdateAsync, so setters can be added with an ordinary if, instead of building an expression tree by hand.
It runs now, outside the change tracker
SaveChanges, and EF Core's docs say it has no interaction with the change tracker at all. Three consequences follow, all reproduced in the test:
Tracked entities keep their old values. A customer loaded before the update still read IsActive == true, and querying it again on the same context returned the same stale instance, because of .A later save can undo the bulk change. Points were raised by 10 for everyone with ExecuteUpdate, then one tracked customer gotPoints += 1andSaveChanges. EF wrote the old value plus 1 for that row, and its bonus was gone.It's a separate database call. It commits on its own unless you put it and your SaveChangesin one explicit transaction.
What SaveChanges did that is now your job
SaveChanges interceptors and overrides don't run, so an UpdatedAt stamp set in a SavingChanges interceptor stayed null. Concurrency tokens aren't checked automatically. And is left to the database. In the test, an order whose lines had a required foreign key was deleted along with its lines by ON DELETE CASCADE. An order with notes on an optional foreign key failed with a foreign key violation, because EF's default for optional relationships, ClientSetNull, sets those keys to null only for entities it tracks, and creates no database rule. Deleted through SaveChanges with the notes loaded, the same order left both notes with a null OrderId.
The fix: let the database do the set-based work
using Microsoft.EntityFrameworkCore;public sealed class DeactivateStaleCustomers(ShopDb db){ public async Task<int> RunAsync(DateTime cutoff, CancellationToken ct) { // Loads, materializes and snapshots every matching row var stale = await db.Customers .Where(c => c.IsActive && c.LastSeenAt < cutoff) .ToListAsync(ct); foreach (var customer in stale) customer.IsActive = false; // One UPDATE per customer, sent in batches return await db.SaveChangesAsync(ct); }}using Microsoft.EntityFrameworkCore;public sealed class DeactivateStaleCustomers(ShopDb db){ public async Task<int> RunAsync(DateTime cutoff, CancellationToken ct) { var now = DateTime.UtcNow; // One UPDATE ... WHERE; nothing is loaded or tracked return await db.Customers .Where(c => c.IsActive && c.LastSeenAt < cutoff) .ExecuteUpdateAsync(s => s .SetProperty(c => c.IsActive, false) // Interceptors don't run here, so stamp it yourself .SetProperty(c => c.UpdatedAt, now), ct); }}Where includes the version the client saw, and the returned count says whether anyone changed the row first.
using Microsoft.EntityFrameworkCore;public sealed class UpdatePrice(ShopDb db){ public async Task<bool> RunAsync( int id, int version, decimal price, bool endSale, CancellationToken ct) { // EF Core 10: a block lambda, so setters can be added conditionally var updated = await db.Products .Where(p => p.Id == id && p.Version == version) .ExecuteUpdateAsync(s => { s.SetProperty(p => p.Price, price); s.SetProperty(p => p.Version, p => p.Version + 1); if (endSale) s.SetProperty(p => p.OnSale, false); }, ct); // 0 rows: the product is gone, or someone changed it first return updated == 1; }}SaveChanges | ExecuteUpdate / ExecuteDelete | |
|---|---|---|
Where, check the count | ||
How to apply it in your project
Find load-modify-save loops Search for queries materialized with ToListAsyncand then changed in aforeach, and forRemoveRangeover a query. Those that change many rows by one rule are candidates.Replace them with one statement Move the filter into Where, the change intoSetProperty, and use the returned count to log, verify or detect conflicts.Take over what SaveChanges did List the interceptors, SaveChangesoverrides, audit columns, domain events and concurrency tokens on that entity, and set or check each one in the statement itself.Check the delete rules Before switching to ExecuteDelete, look at the foreign keys in your migrations. If dependents should be deleted or nulled, configureCascadeorSetNullso the database does it.
Key takeaways
ExecuteUpdateandExecuteDeletesend oneUPDATEorDELETEfor all matching rows, without loading any of them.They run immediately and return the number of rows affected; they aren't part of the next SaveChanges.Tracked entities don't see the change, and saving the same column later overwrites it. Interceptors, audit stamps, concurrency checks and client-side cascades don't happen unless you add them to the statement. Use SaveChangesfor graphs and user edits, and the bulk methods for set-based changes by a rule.
التعليقات (0)