How to Update Rows Without Loading Them in EF Core
Need to update many rows in EF Core?
You don't always need to load them first.
Instead of:
var users = await context.Users
.Where(x => !x.IsActive)
.ToListAsync();
foreach (var user in users)
{
user.Status = UserStatus.Disabled;
}
await context.SaveChangesAsync();You can update matching rows directly:
await context.Users
.Where(x => !x.IsActive)
.ExecuteUpdateAsync(setters => setters
.SetProperty(x => x.Status, UserStatus.Disabled));
ExecuteUpdateAsync() is useful when:
- You need to update many rows
- You don't need the entities in memory
- You don't need change tracking
- The update can be expressed as a database operation
- You want to avoid unnecessary round trips and allocations
The update runs directly in the database.
If you don't need the entities, loading them before updating them is optional.