Detect a stale update with an EF Core concurrency token

An optimistic concurrency token makes an update conditional on the version originally read. If another writer changes that token first, EF Core reports a conflict instead of silently overwriting the newer row.

This SQLite example uses an application-managed Guid token. SQL Server applications can instead map a rowversion column where that matches their model.

Reproduce a conflict

Create a .NET 10 console project and add Microsoft.EntityFrameworkCore.Sqlite version 10.0.0. Replace Program.cs:

C#
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;

using var connection = new SqliteConnection("Data Source=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<Store>().UseSqlite(connection).Options;
using var first = new Store(options);
first.Database.EnsureCreated();
first.Items.Add(new Item { Text = "Original", Version = Guid.NewGuid() });
first.SaveChanges();
using var second = new Store(options);
var a = first.Items.Single();
var b = second.Items.Single();
a.Text = "First writer"; a.Version = Guid.NewGuid();
first.SaveChanges();
b.Text = "Second writer"; b.Version = Guid.NewGuid();
try { second.SaveChanges(); } catch (DbUpdateConcurrencyException) { Console.WriteLine("Conflict detected"); }

public sealed class Store(DbContextOptions<Store> options) : DbContext(options) {
	public DbSet<Item> Items => Set<Item>();
	protected override void OnModelCreating(ModelBuilder model)
		=> model.Entity<Item>().Property(x => x.Version).IsConcurrencyToken();
}
public sealed class Item {
	public int Id { get; set; }
	public string Text { get; set; } = "";
	public Guid Version { get; set; }
}

Run dotnet run. Expect Conflict detected. The two contexts share the open database but maintain separate tracked original values.

Resolve the conflict deliberately

The example reports the conflict and stops. A real editor can load database values, show the competing changes, and ask the user to merge or reload. A retry must update the original concurrency token and apply an explicit policy. Blindly retrying the same stale update is not a resolution. Regenerate an application-managed token for every relevant update, and handle deletion separately when the row no longer exists.

Official references

Handling Concurrency Conflicts - EF Core
Managing conflicts when the same data is updated concurrently with Entity Framework Core
https://learn.microsoft.com/en-us/ef/core/saving/concurrency
EF Core concurrency conflicts

Author: Herman Schoenfeld