Sub topic 16
Bulk Updates and Deletes
You already know the usual way to change data. You load entities, change them, and call SaveChangesAsync. That works well for a few rows. If you need to change thousands of rows, it gets slow. EF Core has to load every row into memory and track each one, then send an UPDATE or DELETE for every row.
A bulk operation is a single SQL command that changes many rows at once. EF Core 7 and later provide two of them: ExecuteUpdateAsync and ExecuteDeleteAsync.
How Bulk Operations Differ
| Approach | Loads rows? | Tracks entities? | Needs SaveChanges? |
|---|---|---|---|
| Load, change, `SaveChangesAsync` | Yes | Yes | Yes |
| `ExecuteUpdateAsync` / `ExecuteDeleteAsync` | No | No | No |
A Worked Example
This code uses the BloggingContext from earlier chapters.
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
// Add " (archived)" to the title of every post in blog 1
int updated = await db.Posts
.Where(p => p.BlogId == 1)
.ExecuteUpdateAsync(s => s.SetProperty(p => p.Title, p => p.Title + " (archived)"));
Console.WriteLine($"Updated {updated} posts");
// Delete every post with empty content
int deleted = await db.Posts
.Where(p => p.Content == "")
.ExecuteDeleteAsync();
Console.WriteLine($"Deleted {deleted} posts");Here is what happens:
Wherepicks the rows to change, the same way it does in a normal query.ExecuteUpdateAsynctakes a list of setters.SetPropertynames a column and gives its new value. The new value can use the old one, asp.Title + " (archived)"does here.ExecuteDeleteAsyncremoves every row that matches the filter.- Each method runs right away and returns the number of rows it changed.
The update becomes SQL roughly like this:
UPDATE "Posts"
SET "Title" = "Title" || ' (archived)'
WHERE "BlogId" = 1;To set more than one column, chain the setters: s.SetProperty(...).SetProperty(...).
When to Use Them
Use bulk operations when:
- You want to change or delete many rows with the same rule.
- You don't need the entities in memory afterward.
Use the normal SaveChangesAsync path when:
- Each row needs different changes based on your C# logic.
- You want to add new rows. Bulk operations cannot insert.
- You need the context to keep its tracked objects in sync.
Exercise
Write a statement that deletes every blog whose Url does not start with "https://", and stores how many rows were removed.
Show answer
int removed = await db.Blogs.Where(b => !b.Url.StartsWith("https://")).ExecuteDeleteAsync(); This sends one DELETE command and needs no call to SaveChangesAsync.
Exercise
You load a blog with FirstAsync, then call ExecuteUpdateAsync to change its Url in the database. What does the loaded blog's Url property show?
Show answer
It still shows the old Url. ExecuteUpdateAsync changes the database directly and does not update entities the context is already tracking.