Multiple users, background jobs, and service instances may update the same database row at the same time. A user might open a product editing page while a scheduled process changes the product price. If the user later submits the original form without any concurrency check, the application can overwrite newer data with stale values. The result may be a lost update involving prices, inventory, permissions, or other business-critical fields.
Entity Framework Core supports optimistic concurrency for this situation. Instead of holding a database lock while a record is being edited, the application reads a version value and verifies that the value is still current when saving. If another operation changed the row in the meantime, EF Core throws DbUpdateConcurrencyException and the application decides how to proceed.
How optimistic concurrency works
The usual design adds a concurrency token to the update or delete condition. Suppose a Person entity contains a version property. EF Core tracks the original token when the entity is queried. When the entity is saved, the generated command includes both the primary key and the original token.
UPDATE People
SET FirstName = @newName
WHERE PersonId = @id AND Version = @originalVersion;If another transaction has already changed the row, the version no longer matches. The database affects zero rows, and EF Core reports that result as a concurrency conflict. The application can then reload the entity, show the user that the record changed, merge selected fields, or abandon the operation.
Choosing a concurrency token
A token can be database-generated or managed by application code. The correct choice depends on the database provider and on which changes should create a conflict.
Using SQL Server rowversion
With SQL Server, a database-generated row version is a common option. It can be configured with the [Timestamp] attribute or with the Fluent API.
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = null!;
public decimal Price { get; set; }
[Timestamp]
public byte[] Version { get; set; } = null!;
}The version is intended for change detection, not for displaying a human-readable timestamp or revision number. If it is exposed through an API, define its representation deliberately and avoid assuming that it carries business meaning.
Managing a token in application code
Some providers do not offer a native automatically changing version type. An application-managed Guid or another suitable value can be used instead.
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = null!;
public Guid Version { get; set; }
}protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>()
.Property(product => product.Version)
.IsConcurrencyToken();
}The application must assign a new value when the relevant data is changed. This responsibility can live in an application service, domain logic, or a suitable SaveChanges interceptor. Centralizing the rule helps prevent one code path from forgetting to refresh the token.
Handling the exception
Configuring a token is only one part of the design. The save operation must define an explicit response for conflicts.
try
{
product.Price = request.Price;
product.Name = request.Name;
await dbContext.SaveChangesAsync(cancellationToken);
}
catch (DbUpdateConcurrencyException)
{
// Reload current data and expose a domain-specific conflict.
throw new ProductWasChangedException(product.Id);
}The correct user experience depends on the workflow. An interactive editor may reload the current row and ask the user to review the differences. An automated command may fetch the latest state, validate its assumptions again, and apply the business operation to that state. Returning a generic database error hides the important fact that the submitted data was stale.
Understand the three value sets
EF Core exposes three useful perspectives when resolving a conflict:
- Current values: The values the application attempted to save.
- Original values: The values read when the entity was loaded.
- Database values: The values currently stored in the database.
These value sets support a deliberate merge strategy. For example, a user may have changed only a description while another process changed the price. The application might preserve the current price and reapply the description. That decision cannot be made safely by a universal algorithm; each field needs to be evaluated according to its business meaning.
A safe retry pattern
Retrying the same SaveChanges call is usually insufficient. If the entity still contains an old original token, the same conflict will occur again. A useful retry flow is:
- Reload the current record from the database.
- Check whether the incoming command is still valid.
- Reapply the business operation to the current state.
- Save using the refreshed token.
- Stop after a bounded number of attempts.
This approach is especially important for inventory, account balances, counters, and quotas. The application should express the operation, such as “decrease available quantity by one,” rather than blindly replacing a value that was read several seconds earlier. A retry limit prevents endless loops and protects the database during periods of heavy contention.
Concurrency with ExecuteUpdate and ExecuteDelete
EF Core’s ExecuteUpdate and ExecuteDelete methods execute set-based commands without using the normal change tracker workflow. Therefore, the automatic concurrency behavior associated with SaveChanges does not apply automatically.
var affectedRows = await dbContext.Products
.Where(product => product.Id == id &&
product.Version == expectedVersion)
.ExecuteUpdateAsync(setters => setters
.SetProperty(product => product.Price, newPrice)
.SetProperty(product => product.Version, Guid.NewGuid()),
cancellationToken);
if (affectedRows == 0)
{
throw new ProductWasChangedException(id);
}The token is included explicitly in the predicate, and the affected-row count is checked. A result of zero can mean that the row does not exist or that its version changed. If those cases require different responses, perform an additional existence check or use a domain-specific command design.
When should a transaction be added?
A concurrency token protects the assumption that a particular row has not changed since it was read. A transaction is a separate concern: it makes a group of database operations succeed or fail as one unit. When the provider supports transactions, EF Core applies the changes from a single SaveChanges call transactionally. If several save operations must belong to one atomic workflow, an explicit transaction may be appropriate.
Do not keep a transaction open while waiting for a user to edit a form or approve an action. Long-lived transactions can hold resources and increase contention. For user-facing workflows, short database operations combined with a concurrency token are usually a better fit.
Implementation checklist
- Define a concurrency token for entities where lost updates matter.
- Document whether the database or the application changes the token.
- Convert
DbUpdateConcurrencyExceptioninto a meaningful application-level result. - Reload and reapply the business operation before retrying automatically.
- Bound the number of retry attempts.
- Check affected rows when using set-based update or delete methods.
- Keep explicit transactions short and separate from client interaction.
- Test conflicts with two independent contexts or concurrent test workers.
Optimistic concurrency is not a replacement for every locking or transaction strategy. It is a focused mechanism for detecting stale writes without keeping a lock throughout a user workflow. A robust implementation defines the token, detects the conflict, and provides a business-aware resolution path instead of silently discarding someone’s changes.
0 Comments