Optimistic Concurrency in EF Core with rowversion

Two people edit the same record and the second save silently wins. Stop lost updates with a rowversion column and a clear message.

R M Shahidul Islam Shahed · 4 min read

Two editors open the same post. One fixes a typo and saves. The other, still looking at the old version, rewrites a paragraph and saves. The typo fix is gone and nobody knows. That's a lost update, and it happens in every app with forms and more than one user. EF Core prevents it with optimistic concurrency. This guide sets it up with SQL Server's rowversion and handles the conflict in a way users understand. Examples use EF Core 10 on .NET 10 with SQL Server.

Optimistic vs pessimistic

  • Pessimistic locking blocks other users while one is editing. It doesn't fit web apps: people open a form and go to lunch.
  • Optimistic concurrency lets everyone edit, then checks at save time whether the row changed since you loaded it. If it did, the save is rejected.

For forms, optimistic is the right default.

Add a rowversion column

SQL Server's rowversion is an 8-byte value the database changes automatically on every update.

csharp
public sealed class Post
{
    public int Id { get; set; }
    public string Title { get; set; } = "";
    public string Body { get; set; } = "";
    public byte[] RowVersion { get; set; } = [];
}
csharp
builder.Entity<Post>().Property(p => p.RowVersion).IsRowVersion();

IsRowVersion() marks it as a concurrency token that the database generates. Add a migration and every update now includes it:

sql
UPDATE [Posts] SET [Title] = @p0
OUTPUT INSERTED.[RowVersion]
WHERE [Id] = @p1 AND [RowVersion] = @p2;

If another save changed the row, RowVersion no longer matches, no row is updated, and EF Core throws DbUpdateConcurrencyException.

The step everyone forgets: round-trip the version

In a web app the entity you save isn't the one you showed. The form is loaded in one request and saved in another. The check only works if the original version travels with the form.

Send it to the browser as Base64:

html
<input type="hidden" name="RowVersion" value="@Convert.ToBase64String(Model.RowVersion)">

On save, load the entity and tell EF Core which version the user started from:

csharp
public async Task<SaveResult> SaveAsync(EditPostRequest request, CancellationToken ct)
{
    var post = await db.Posts.FirstOrDefaultAsync(p => p.Id == request.Id, ct);
    if (post is null)
    {
        return SaveResult.NotFound;
    }

    // Compare against the version the user loaded, not the one we just read.
    db.Entry(post).Property(p => p.RowVersion).OriginalValue = Convert.FromBase64String(request.RowVersion);

    post.Title = request.Title;
    post.Body = request.Body;

    try
    {
        await db.SaveChangesAsync(ct);
        return SaveResult.Saved(Convert.ToBase64String(post.RowVersion));
    }
    catch (DbUpdateConcurrencyException)
    {
        return SaveResult.Conflict;
    }
}

Without setting OriginalValue, EF Core compares against the version it loaded a moment ago, which always matches. The check passes and the lost update still happens.

Return the new version after every save

After a successful save the row has a new RowVersion. Send it back and update the hidden field. Otherwise the user's second save in the same form fails as a conflict with themselves.

javascript
const result = await postForm(form);
if (result.success) {
  form.elements.RowVersion.value = result.data.rowVersion;
}

Tell the user what happened

A conflict isn't an error the user caused, and "Something went wrong" helps nobody. Say what happened and what to do:

This post was changed by someone else. Reload to see the latest version.

Keep their unsaved text on screen so they can copy it before reloading. For long-form editing, saving revisions on every save means nothing is ever truly lost.

Concurrency without a rowversion column

If you can't add a column (a legacy table, or another database), mark ordinary properties as concurrency tokens:

csharp
builder.Entity<Product>().Property(p => p.Price).IsConcurrencyToken();

The WHERE clause then includes Price = @original. It only protects the properties you mark, so a rowversion is the better choice where you can use one.

Bulk updates skip the check

ExecuteUpdateAsync and ExecuteDeleteAsync send SQL straight to the database and don't use concurrency tokens. If you need the check there, add it yourself:

csharp
var updated = await db.Posts
    .Where(p => p.Id == id && p.RowVersion == originalVersion)
    .ExecuteUpdateAsync(s => s.SetProperty(p => p.Status, PostStatus.Published), ct);

if (updated == 0) { /* conflict or gone */ }

This "conditional update" pattern also makes background jobs safe to run twice: only the first run's WHERE still matches.

Test it

A concurrency rule deserves a test, because nothing visibly breaks when it's missing.

csharp
[Fact]
public async Task Save_WithStaleRowVersion_IsRejected()
{
    var (id, original) = await CreatePostAsync();
    await service.SaveAsync(new(id, "First edit", "…", original), default);

    var second = await service.SaveAsync(new(id, "Second edit", "…", original), default);

    Assert.Equal(SaveResult.Conflict, second);
}

Wrapping up

Add a rowversion, mark it with IsRowVersion(), send the original value through the form, set it as OriginalValue before saving, and return the new value after. Those five steps turn silent lost updates into a clear message, at the cost of one 8-byte column.

Keep reading

All articles →
EF Core & Databases

Fast Read Queries in EF Core 10: Projections, No-Tracking and Paging

Most slow EF Core pages come from four habits. Fix them with projections, AsNoTracking, database paging and split queries, and check the SQL.

4 min read
EF Core & Databases

12 EF Core Performance Tips That Actually Matter

AsNoTracking, compiled queries, split queries and bulk updates — measured on a real ERP database, not a toy sample.

1 min read
Security

Security Headers and CSP in ASP.NET Core Without Breaking Your Site

Add CSP, HSTS and the other security headers with one small middleware, keep inline scripts working by hash, and roll it out without breaking pages.

4 min read