Covers EF Core optimistic concurrency: [Timestamp]/IsRowVersion on SQL Server rowversion, app-managed concurrency tokens with IsConcurrencyToken, the UPDATE ... WHERE RowVersion = @original pattern, setting OriginalValue from the client, DbUpdateConcurrencyException with GetDatabaseValuesAsync and store-wins/client-wins/merge resolution, concurrency with ExecuteUpdate, and mapping to 409 or ETag/If-Match with 412.
Optimistic concurrency assumes conflicts are rare: nobody holds locks, and each write checks that the row hasn't changed since it was read. On SQL Server, add a [Timestamp] byte[] RowVersion (IsRowVersion()), which the database updates on every write; or mark an app-managed property with IsConcurrencyToken(). EF Core then sends UPDATE ... WHERE Id = @id AND RowVersion = @original; zero rows affected throws DbUpdateConcurrencyException. In an API, send the version to the client (often as an ETag), and on the way back set it as the entity's OriginalValue. On conflict, choose store wins (reload and tell the user), client wins (overwrite) or a merge, and return 409 Conflict (or 412 for a failed If-Match). The trade-off: no blocking and good scalability, at the cost of handling conflicts explicitly.
"Optimistic concurrency is about lost updates. Two people load the same record, both edit it, and without a check the second save silently overwrites the first. Instead of locking the row while someone has it open, which doesn't work across HTTP anyway, I keep a version on the row and make every update conditional on it.
On SQL Server the easy way is a
rowversioncolumn:[Timestamp] public byte[] RowVersion. SQL Server bumps it on every update, so I never set it myself. EF Core puts the original value it loaded into theWHEREclause and addsOUTPUT INSERTED.RowVersionto get the new one. If the row changed, theWHEREmatches nothing, EF sees zero rows affected and throwsDbUpdateConcurrencyException. If I can't userowversion, I mark any property withIsConcurrencyToken()and change it myself on every save, a Guid for example.The part people get wrong is the disconnected case. The request that saves isn't the request that loaded. So the GET returns the version, often as an ETag header, and the PUT sends it back. I load the entity, then set
Entry(e).Property(x => x.RowVersion).OriginalValueto the client's value. Setting the current value does nothing useful, because EF compares using the original. When the exception fires,ex.Entriesgives me the entity;GetDatabaseValuesAsync()gives the current row. Then it's a business decision: store wins means reload and return 409 with the latest state; client wins means copy the database values intoOriginalValuesand save again; merge means applying non-overlapping field changes. With ETags I useIf-Matchand return 412 when it doesn't match. The mistake I see is catching the exception and retrying blindly. That's just a slower lost update."
| Strategy | Config | Who changes it | Notes |
|---|---|---|---|
rowversion |
[Timestamp] or IsRowVersion() |
SQL Server, every update | 8 bytes, unique per database; the default choice |
| App-managed token | IsConcurrencyToken() on e.g. Guid Version |
Your code, every save | Works on any provider; easy to forget to change |
| Column as token | IsConcurrencyToken() on Status |
Normal edits | Detects conflicts on that column only |
| Option | What you do | Use when |
|---|---|---|
| Store wins | Reload, return 409 with current state | Default for user edits |
| Client wins | entry.OriginalValues.SetValues(dbValues), save again |
Last writer genuinely should win (rare) |
| Merge | Compare proposed, original and database values per property | Different fields edited, low risk |
| Situation | Response |
|---|---|
| Version in body is stale | 409 Conflict (ProblemDetails, current version) |
If-Match ETag doesn't match |
412 Precondition Failed |
If-Match required but missing |
428 Precondition Required |
Adding rowversion checks to a [rostering] API surfaced [~30] conflicts a day that had been silent overwrites; the UI showed 'someone else changed this shift' with a diff, and complaints about 'disappearing changes' stopped.
Checks the candidate can implement optimistic concurrency end to end in an EF Core API, including the disconnected case and conflict handling.
Green flags
WHERE RowVersion = @original mechanism and zero-rows detection.OriginalValue.ExecuteUpdate needs the check by hand.Red flags
T1 Alice GET shift 7 (Start 09:00)
T2 Bob GET shift 7 (Start 09:00)
T3 Alice PUT Start 08:00 -> UPDATE ... SET Start='08:00' WHERE Id=7
T4 Bob PUT Notes='x' -> UPDATE ... SET Start='09:00', Notes='x' WHERE Id=7 (Alice's change lost)
UPDATE [Shifts] SET [Start] = @p0
OUTPUT INSERTED.[RowVersion]
WHERE [Id] = @p1 AND [RowVersion] = @p2; -- @p2 = original value
EF checks the affected row count per statement in the batch. Zero means conflict, and the whole SaveChanges transaction rolls back. Deletes are checked too (DELETE ... WHERE Id AND RowVersion).
Entry(shift).Property(s => s.RowVersion)
OriginalValue -> goes in WHERE <- set the client's version HERE
CurrentValue -> ignored for rowversion (store-generated)
catch (DbUpdateConcurrencyException ex)
{
var entry = ex.Entries.Single();
var proposed = entry.CurrentValues; // what we tried to write
var original = entry.OriginalValues; // what we thought was there
var database = await entry.GetDatabaseValuesAsync(ct); // what is there now (null if deleted)
}
A null from GetDatabaseValuesAsync means the row was deleted: return 404 or 410.
ExecuteUpdateAsync doesn't go through the change tracker, so tokens aren't added automatically:
var rows = await db.Shifts.Where(s => s.Id == id && s.RowVersion == version)
.ExecuteUpdateAsync(s => s.SetProperty(x => x.Start, start), ct);
if (rows == 0) /* conflict or not found */;
Encode the rowversion as Base64 in an ETag ("AAAAAAAAB9E="). GET returns ETag; PUT/PATCH sends If-Match. Standards-wise, a failed If-Match is 412. Weak vs strong ETags: use strong for writes. Caches and proxies can use the same ETag with If-None-Match for 304 responses on reads.
Pessimistic (SELECT ... WITH (UPDLOCK, ROWLOCK) in a transaction) blocks others while you hold the lock: good for short, high-contention server-side operations like allocating stock, never across a user's think-time.
[Timestamp], load the same entity in two contexts, save both, and catch the exception.GetDatabaseValuesAsync output.ExecuteUpdateAsync with the version in Where and check the row count.curl calls.A Minimal API update with rowversion, ETag/If-Match and store-wins conflict handling.
namespace Rostering.Shifts;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
public sealed class Shift
{
public int Id { get; set; }
public TimeOnly Start { get; set; }
public TimeOnly End { get; set; }
public string? Notes { get; set; }
[Timestamp] public byte[] RowVersion { get; set; } = []; // SQL Server rowversion
}
public sealed record ShiftDto(int Id, TimeOnly Start, TimeOnly End, string? Notes);
public sealed record UpdateShift(TimeOnly Start, TimeOnly End, string? Notes);
public static class ShiftEndpoints
{
public static void MapShifts(this IEndpointRouteBuilder app)
{
app.MapGet("/shifts/{id:int}", async (int id, RosterDbContext db, HttpContext http, CancellationToken ct) =>
{
var s = await db.Shifts.AsNoTracking().SingleOrDefaultAsync(x => x.Id == id, ct);
if (s is null) return Results.NotFound();
http.Response.Headers.ETag = $"\"{Convert.ToBase64String(s.RowVersion)}\"";
return Results.Ok(new ShiftDto(s.Id, s.Start, s.End, s.Notes));
});
app.MapPut("/shifts/{id:int}", async (int id, UpdateShift req, RosterDbContext db, HttpContext http, CancellationToken ct) =>
{
var ifMatch = http.Request.Headers.IfMatch.ToString().Trim('"');
if (string.IsNullOrEmpty(ifMatch)) return Results.StatusCode(StatusCodes.Status428PreconditionRequired);
var shift = await db.Shifts.SingleOrDefaultAsync(x => x.Id == id, ct);
if (shift is null) return Results.NotFound();
// The client's version must be the ORIGINAL value: that is what goes in the WHERE clause.
db.Entry(shift).Property(x => x.RowVersion).OriginalValue = Convert.FromBase64String(ifMatch);
shift.Start = req.Start;
shift.End = req.End;
shift.Notes = req.Notes;
try
{
await db.SaveChangesAsync(ct);
}
catch (DbUpdateConcurrencyException ex)
{
// Store wins: tell the client what is there now; they decide what to do.
var current = await ex.Entries.Single().GetDatabaseValuesAsync(ct);
if (current is null) return Results.NotFound();
http.Response.Headers.ETag = $"\"{Convert.ToBase64String(current.GetValue<byte[]>(nameof(Shift.RowVersion)))}\"";
return Results.Problem("The shift was changed by someone else. Reload and reapply your changes.",
statusCode: StatusCodes.Status412PreconditionFailed);
}
http.Response.Headers.ETag = $"\"{Convert.ToBase64String(shift.RowVersion)}\""; // new version from OUTPUT
return Results.NoContent();
});
}
}
// Client wins, for the rare case it is correct: refresh originals from the database and save again.
catch (DbUpdateConcurrencyException ex)
{
foreach (var entry in ex.Entries)
{
var dbValues = await entry.GetDatabaseValuesAsync(ct);
if (dbValues is null) continue; // deleted: decide separately
entry.OriginalValues.SetValues(dbValues); // next save's WHERE uses the latest version
}
await db.SaveChangesAsync(ct);
}
WHERE, which is the freshly loaded version, so the check always passes. Instead: set Property(x => x.RowVersion).OriginalValue.DbUpdateConcurrencyException and automatically re-running the same save with refreshed originals for user edits. Why it is wrong: that is client wins by accident: it overwrites the other user's change without anyone seeing it, which is the lost update you were preventing. Instead: retry automatically only where overwriting is correct by design (an idempotent sync job, or a server-side operation that re-reads and re-applies its logic to the fresh values); for user edits, surface the conflict.null from GetDatabaseValuesAsync. Why it is wrong: it means the row was deleted, and treating it as a normal conflict throws or re-inserts. Instead: return 404 or 410.rowversion, or set the token centrally in a SaveChangesInterceptor.ExecuteUpdate checks concurrency tokens. Why it is wrong: it bypasses the change tracker, so no version check is added. Instead: include the version in Where and check rows affected.If-Match) with ProblemDetails.I make concurrency checks the default for every user-editable aggregate, not an add-on after the first incident. rowversion costs 8 bytes a row and one predicate; the bug it prevents is silent data loss that nobody notices until a customer does. The conflict strategy is a product decision: for most screens store wins with a clear message and a diff is right; merging is only worth it for high-collaboration records.
I also check the non-UI paths: background jobs updating the same rows need the same check or set-based ExecuteUpdate with the version in the predicate, and integration tests should prove a stale write fails. I watch the conflict rate per endpoint; a high rate suggests the aggregate is too coarse and should be split.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
rowversion + store wins |
User edits | Conflict UX | Never wrong as a default |
| Client wins | Idempotent overwrites, sync jobs where last write is right | Can hide real conflicts | Shared human-edited records |
| Merge per field | Collaborative records, low overlap | Complexity, testing | Financial values |
Pessimistic lock (UPDLOCK) |
Short server-side critical sections | Blocking, deadlocks | Across user think-time |
I'd rank the findings by impact:
Status or OwnerId.Update() on an already-tracked entity is redundant and marks every column modified.NullReferenceException (500, not 404), and it returns the entity instead of a DTO.The rewrite: a use-case DTO with only editable fields plus RowVersion, load filtered by owner, set the RowVersion original value, assign fields explicitly, SaveChangesAsync, and map DbUpdateConcurrencyException to 409. The trade-off is a few lines of explicit mapping in exchange for correct, minimal, secure updates.
All three walk the whole graph and set states based on whether each entity has a key value:
Add: everything becomes Added, so EF Core inserts it.Attach: entities with a key become Unchanged, without one become Added. Nothing is written until you change something.Update: entities with a key become Modified with every property marked, because EF Core has no original values to compare with, so it writes every column.That makes Update dangerous for APIs: it overwrites columns the client never meant to change and silently loses concurrent edits. Better: accept a use-case DTO containing only the editable fields (so nothing can be over-posted), load the entity tracked and apply the DTO so only real changes are written, use Attach plus IsModified for a known partial update, or ExecuteUpdate for set-based changes, always with a RowVersion set as the original value. The trade-off is one extra read in exchange for correct, minimal updates.
db.Entry(entity) returns an EntityEntry<T>, the change tracker's view of one entity:
State, CurrentValues, OriginalValues and GetDatabaseValuesAsync() for state and values.Property(p => p.X) gives CurrentValue, OriginalValue and IsModified, so you can mark one column for update, or set the RowVersion original value for a concurrency check.Collection(...)/Reference(...) give explicit loading (LoadAsync, IsLoaded) and Query() to filter or count related rows without loading them all.CurrentValues.SetValues(dto) copies matching values; ReloadAsync() discards local changes.For disconnected graphs, ChangeTracker.TrackGraph visits each node so you choose its state. The trade-off: it gives precise control, but it is easy to misuse (setting current instead of original values, or calling Entry() in hot loops).
How to tell it (STAR)
**S:** At [company], managers using our [rostering] app kept reporting that shift times reverted, and [carers turned up at the wrong time]. **T:** I was asked to find out why, since nothing appeared in the error logs. **A:** Matching complaints to request logs showed two managers saving the same shift within seconds; the second save carried stale values for fields they hadn't touched. I added a rowversion column, sent it as an ETag, required If-Match on updates, returned 412 with the latest data, and worked with the front-end developer on a dialog that showed both versions. **R:** The complaints stopped within [two weeks], and the dashboard showed [~30] conflicts a day being caught that used to be silent overwrites.
Last updated 23 Nov 2026.