Sub topic 16
Bulk Updates and Deletes
Until now, every change you made followed the same three steps. You loaded entities from the database, changed them in C#, and called SaveChangesAsync. That works well for a few rows. It gets slow when you need to change thousands of rows at once.
This chapter shows a faster way. EF Core 7 and later include two methods, ExecuteUpdateAsync and ExecuteDeleteAsync. They change rows directly in the database without loading them first.
The Problem with Loading Everything
Say you want to mark every post in blog 1 as archived. With the method you already know, the code looks like this:
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
var posts = await db.Posts
.Where(p => p.BlogId == 1)
.ToListAsync();
foreach (var post in posts)
{
post.Title = post.Title + " (archived)";
}
await db.SaveChangesAsync();This code does a lot of work:
- It runs a
SELECTthat copies every matching post from the database into memory. - The change tracker stores a snapshot of each post. The change tracker is the part of the DbContext that remembers what each entity looked like when it was loaded.
- Your loop changes each title.
SaveChangesAsynccompares every entity with its snapshot and sends oneUPDATEper changed row. EF Core groups these statements into batches, but each row still gets its own statement.
For 10 posts, that cost is small. For 100,000 posts, you move a lot of data over the network and use a lot of memory, all for a change the database could make in one statement.
ExecuteUpdateAsync: Change Rows in Place
A bulk operation is a single SQL command that changes many rows at once. ExecuteUpdateAsync builds one for you:
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
int updated = await db.Posts
.Where(p => p.BlogId == 1)
.ExecuteUpdateAsync(s => s.SetProperty(p => p.Title, p => p.Title + " (archived)"));
Console.WriteLine($"{updated} posts archived");Here is what each part does:
Where(p => p.BlogId == 1)chooses the rows. It works like the filters in your LINQ queries.SetPropertynames a property and gives it a new value. The first lambda picks the column (p.Title). The second lambda computes the new value, and it can use the row's current values.- The method returns an
int, the number of rows the database changed.
EF Core turns this into a single SQL statement. On SQLite it looks roughly like this:
UPDATE "Posts" AS "p"
SET "Title" = "p"."Title" || ' (archived)'
WHERE "p"."BlogId" = 1No rows come back to your program. The database does all the work.
Setting Several Columns
To change more than one column, chain SetProperty calls. A plain value also works when the new value does not depend on the old one:
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
int updated = await db.Posts
.Where(p => p.Content == "")
.ExecuteUpdateAsync(s => s
.SetProperty(p => p.Title, "Untitled draft")
.SetProperty(p => p.Content, "Coming soon"));All of these changes go into one UPDATE statement.
ExecuteDeleteAsync: Remove Rows in Place
ExecuteDeleteAsync works the same way for deleting. You filter the rows, then delete them all with one command:
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
int deleted = await db.Posts
.Where(p => p.Content == "")
.ExecuteDeleteAsync();
Console.WriteLine($"{deleted} empty posts deleted");The SQL is a single DELETE ... WHERE statement. Compare that with the Remove method from the CRUD chapter, which needs each entity loaded before you can delete it.
How the Two Approaches Compare
| Question | Load, change, SaveChanges | ExecuteUpdate / ExecuteDelete |
|---|---|---|
| Are rows loaded into memory? | Yes | No |
| Are entities tracked? | Yes | No |
| SQL statements sent | One per changed row | One in total |
| Runs when you call it? | No, waits for SaveChanges | Yes, right away |
| Checks concurrency tokens? | Yes | No |
| Good for | A few rows, complex C# logic | Many rows, simple rules |
Edge Cases to Watch For
Bulk methods skip the change tracker. That makes them fast, and it also causes the surprises listed below.
Tracked Entities Go Stale
If your context already has a post loaded, a bulk update does not change that object in memory. The database has the new value, but your C# object still holds the old one:
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
var post = await db.Posts.FirstAsync(p => p.BlogId == 1);
Console.WriteLine(post.Title); // "Hello"
await db.Posts
.Where(p => p.BlogId == 1)
.ExecuteUpdateAsync(s => s.SetProperty(p => p.Title, "Changed"));
Console.WriteLine(post.Title); // Still "Hello" in memory
await db.Entry(post).ReloadAsync();
Console.WriteLine(post.Title); // "Changed"ReloadAsync reads the row again from the database. Another option is to use a new DbContext after a bulk operation.
They Run Immediately
ExecuteUpdateAsync and ExecuteDeleteAsync send their SQL as soon as you call them. They are not saved later by SaveChangesAsync, and SaveChangesAsync does not include them. If a bulk command and a SaveChangesAsync call need to succeed or fail together, wrap both in an explicit transaction. The Transactions chapter shows how.
No Concurrency Checks
Concurrency tokens, covered in a later chapter, are not checked. A bulk update overwrites whatever is in the row, even if another user changed it a moment earlier.
Deleting Related Rows
When you delete a blog with ExecuteDeleteAsync, EF Core does not delete its posts for you. The database's own foreign key rules decide what happens. If the migration set up cascade delete, the database removes the posts. If it did not, the delete fails with a foreign key error. To be safe, delete the child rows first:
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
await db.Posts.Where(p => p.BlogId == 1).ExecuteDeleteAsync();
await db.Blogs.Where(b => b.BlogId == 1).ExecuteDeleteAsync();Logic That Must Be SQL
The values in SetProperty must be something EF Core can translate into SQL. Simple math, string joining, and constants all work. A call to your own C# method, such as FormatTitle(p.Title), cannot run inside the database, so EF Core throws an error. When the change needs real C# logic, use the load-and-save approach instead.
Exercises
Exercise
Write one statement that sets the Url of every blog whose Url starts with "http://" to the same address with "https://" instead. Hint: SQLite's REPLACE is used when you call string.Replace.
Show answer
int count = await db.Blogs.Where(b => b.Url.StartsWith("http://")).ExecuteUpdateAsync(s => s.SetProperty(b => b.Url, b => b.Url.Replace("http://", "https://"))); EF Core translates the filter and the Replace call into a single UPDATE statement, and count holds the number of rows changed.
Exercise
You load a blog, then run ExecuteUpdateAsync to change its Url, then print blog.Url. Which value is printed, and why?
Show answer
The old Url is printed. ExecuteUpdateAsync changes the row in the database but does not touch entities the change tracker already holds. Call await db.Entry(blog).ReloadAsync() or use a new DbContext to see the new value.
Exercise
What happens if you run db.Posts.ExecuteDeleteAsync() with no Where call, and what does the method return?
Show answer
It deletes every row in the Posts table immediately, without waiting for SaveChanges. It returns the number of rows deleted.