الانتقال إلى المحتوى
.NETEF Core· 8 دقائق للقراءة

You Don't Have to Load Entities to Update Them: ExecuteUpdate and ExecuteDelete

One UPDATE or DELETE statement replaces loading thousands of rows. The price is that the change tracker, and everything SaveChanges did for you, is out of the loop.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • EF Core 10
محتويات المقال

A nightly job deactivates customers who haven't signed in for two years. It loads every match, sets 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

The belief: EF Core changes data through the change tracker, and only through it. To update or delete rows you query them, change or remove the entities, and call SaveChanges. Anything else means dropping down to raw SQL.

It's how EF is taught, and for a long time it was true. Bulk operations only arrived in EF Core 7.0, so years of tutorials, answers and code reviews predate them. The tracked approach also feels efficient, because 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

The tracked path brings every matching row to the client, materializes an entity for each, snapshots its values in the , compares each entity with its snapshot when you save, and then sends one 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.

In a test with EF Core 10 on SQL Server LocalDB, deactivating 40,000 of 50,000 customers this way took 954 commands: one 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.

The same 40,000-row job became one command, ran in about 120 ms and allocated almost nothing, because no row ever left the database. EF Core 10 also lets you pass a regular block lambda to 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

The statement runs the moment you await it. It isn't queued for 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 got Points += 1 and SaveChanges. 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 SaveChanges in 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

C# DeactivateStaleCustomers.cs
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);    }}

It also works for a single row you never loaded. Here a price change carries its own concurrency check: the Where includes the version the client saw, and the returned count says whether anyone changed the row first.

C# UpdatePrice.cs
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;    }}
Load + SaveChangesExecuteUpdate / ExecuteDelete
Rows loaded into memoryEvery matchNone
Statements sentOne per row, in batchesOne for all rows
Tracked entitiesUp to dateKeep their old values
Interceptors and audit stampsRunDon't run: set the columns yourself
Concurrency tokensChecked for youPut them in Where, check the count
Optional dependents on deleteKeys set to null if loadedDatabase rule applies; may fail

How to apply it in your project

  1. Find load-modify-save loopsSearch for queries materialized with ToListAsync and then changed in a foreach, and for RemoveRange over a query. Those that change many rows by one rule are candidates.
  2. Replace them with one statementMove the filter into Where, the change into SetProperty, and use the returned count to log, verify or detect conflicts.
  3. Take over what SaveChanges didList the interceptors, SaveChanges overrides, audit columns, domain events and concurrency tokens on that entity, and set or check each one in the statement itself.
  4. Check the delete rulesBefore switching to ExecuteDelete, look at the foreign keys in your migrations. If dependents should be deleted or nulled, configure Cascade or SetNull so the database does it.

Key takeaways

  • ExecuteUpdate and ExecuteDelete send one UPDATE or DELETE for 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 SaveChanges for graphs and user edits, and the bulk methods for set-based changes by a rule.

📚 المصادر

  1. ExecuteUpdate and ExecuteDelete — EF Core, Microsoft Learn
  2. Efficient Updating — EF Core, Microsoft Learn
  3. Saving Data — EF Core, Microsoft Learn
  4. What's New in EF Core 10 — Microsoft Learn
  5. Cascade Delete — EF Core, Microsoft Learn

التعليقات (0)