Course outline

ASP.NET Core / Intermediate: Data, Identity, and Asynchronous Work / Lesson 14

Optimistic concurrency with EF Core

Detect conflicting edits with a concurrency token and define a safe conflict response.

About 4 min readContent reviewed
On this page

Lesson goals

  • Explain optimistic concurrency and a tracked original token.
  • Handle a save conflict without silently overwriting another edit.
  • Test two independent contexts against the intended database provider.

Recognize the lost-update risk

Two users can load the same record and make different edits before either saves. Without a concurrency strategy, the later save may overwrite the earlier decision. EF Core can include a configured concurrency token’s original value in an update condition and report a conflict when the expected row is not updated. A token detects a conflict; the application still decides how to inform the user or resolve it.

Configure the token deliberately

The first example uses the Timestamp attribute for a SQL Server rowversion-style property on an existing model. Provider support and token generation differ, so do not assume the same attribute creates a database-generated token on every engine. Apply and review the migration for the chosen provider. Decide which changes should create a conflict and how the client receives and returns the appropriate version for disconnected updates.

csharp A SQL Server-oriented rowversion property
using System.ComponentModel.DataAnnotations;

public class Document
{
    public int Id { get; set; }
    public string Title { get; set; } = "";
    [Timestamp]
    public byte[] Version { get; set; } = Array.Empty<byte>();
}

This model fragment assumes SQL Server support and a migration. Other providers may need a different token strategy.

Handle conflict as a domain outcome

The second fragment catches DbUpdateConcurrencyException when saving an existing context. Return an intentional conflict response or present current values for a user decision; do not blindly retry a stale overwrite. More complex merges need explicit business rules and a bounded retry policy. The fragment does not implement a controller or choose an HTTP status, and it must not expose sensitive database values to an unauthorized user.

csharp Handle a conflict at the save boundary
try
{
    await db.SaveChangesAsync(cancellationToken);
}
catch (DbUpdateConcurrencyException)
{
    // Return a safe conflict outcome or invoke an explicit merge policy.
}

Choose an application-specific resolution or error response. Do not treat every database exception as a concurrency conflict.

Protect the entire decision

A concurrency token on one row does not automatically enforce an invariant spanning several rows or an external system. Use suitable constraints, transaction isolation or a carefully designed conditional update for the actual invariant, and test on the target database. When a client retries after an uncertain network timeout, also consider operation idempotency; concurrency detection and duplicate-effect prevention solve different problems.

Exercise two independent editors

In a disposable database with the intended provider, load the same row in two contexts. Save a change from the first, then attempt a conflicting save from the second and assert the exception or mapped conflict response. Inspect the stored value and token afterward. Test deletion and an authorized nonconflicting path as well. An in-memory substitute may not reproduce the provider’s concurrency-token behavior.

Common errors and fixes

The later edit silently replaces the earlier one

Why it happens
No effective concurrency token or conflict handling was configured.
How to fix it
Configure and test a token supported by the target provider.
Prevent it next time
Exercise two independent contexts.

A conflict is retried until the stale edit wins

Why it happens
The application retries without reloading or applying a merge policy.
How to fix it
Present a conflict or apply explicit business rules to current data.
Prevent it next time
Test bounded retries and preserve the earlier edit.

A row token is assumed to protect an external effect

Why it happens
The database token does not cover the other system.
How to fix it
Use a separate idempotency or reconciliation design.
Prevent it next time
Test a timeout and repeated external operation.

2 practice exercises

1. Two editors load version A; the first saves version B. What should happen when the second saves A?

Show worked solution

A correctly configured concurrency token detects that the original version no longer matches and EF Core reports a conflict. The application should preserve B and present a safe resolution or apply a documented merge.

2. Does a rowversion automatically prevent sending the same email twice?

Show worked solution

No. It protects an update condition in the database, not an independent mail provider. Use a stable operation identity and a provider or application idempotency strategy, then test uncertain delivery.

Key takeaways

  • A concurrency token detects stale writes; the application owns resolution.
  • Verify provider behavior and multi-system effects separately.

Official references