skip to content

In an EF Core 10 Web API, why can a ticket edit posted with its version still overwrite a newer change?

level: middleimportance: should knowfreq 48%

answer

  1. the WHERE uses OriginalValue
  2. load then SetValues copies the current value
  3. Property(t => t.Version).OriginalValue
  4. Update sets original equal to current
  5. 409 Conflict with fresh values

basics

~10 s

EF Core checks the token's original value, and after loading a fresh row that is the newest version, not the one the client saw. Set Entry(ticket).Property(t => t.Version).OriginalValue to the posted version before saving.

solid answer

~40 s

The client loaded ticket 4711 at version A, the agent edited it for ten minutes, and meanwhile a colleague saved version B. On submit, a handler that runs `FindAsync` and then `CurrentValues.SetValues(dto)` has just loaded version **B** as the original value; copying `dto.Version` only sets the current value, which EF Core ignores for a row version. The `UPDATE ... WHERE "xmin" = B` matches and the colleague's change is lost. The fix is one line: `db.Entry(ticket).Property(t => t.Version).OriginalValue = dto.Version;` - now the `WHERE` carries A, matches nothing, and `SaveChanges` throws `DbUpdateConcurrencyException`, which the endpoint turns into `409 Conflict`. An `Update(ticket)` built from the posted data already works, because attaching makes the original value equal to the posted one.

code

csharp · 18 lines
csharp
app.MapPut("/tickets/{id:int}", async (int id, TicketEditDto dto, HelpdeskDbContext db, CancellationToken ct) =>
{
    var ticket = await db.Tickets.FindAsync([id], ct);
    if (ticket is null) return Results.NotFound();

    db.Entry(ticket).CurrentValues.SetValues(dto);
    db.Entry(ticket).Property(t => t.Version).OriginalValue = dto.Version;   // the version the agent saw

    try
    {
        await db.SaveChangesAsync(ct);
        return Results.NoContent();
    }
    catch (DbUpdateConcurrencyException)
    {
        return Results.Problem(statusCode: StatusCodes.Status409Conflict, title: "The ticket was changed by someone else.");
    }
});

go deeper

for a junior

Know that the client must send the version it loaded back with its edit.

for a middle

Explain why EF Core uses the original value, and set OriginalValue after a load-then-apply update.

for a senior

Spot the fresh-load bug in code review, require the token in the contract, return 409 or 412, and test with an interleaved save.

for a principal

Standardise how versioned resources expose tokens - body field or ETag - across a team's APIs and clients.

## Where the version has to come from Optimistic concurrency protects the **edit the user made**, so the token EF Core checks must be the one that user **saw** when the edit started. In a web app, that value leaves the server with the GET response and comes back with the PUT. EF Core puts a concurrency token's **original value** into the `WHERE` clause, so the job is to make the posted version the original value of the entity you save. ## The common bug A helpdesk endpoint updates a ticket like this: ```csharp var ticket = await db.Tickets.FindAsync(id); // loads the CURRENT row, version B db.Entry(ticket!).CurrentValues.SetValues(dto); // dto.Version (A) becomes the current value await db.SaveChangesAsync(); // WHERE "Id" = @id AND "xmin" = B ``` Step by step: 1. Agent X opened ticket 4711 when it was at version A; the client keeps `Version = A`. 2. Agent Y saves a reply; the row moves to version B. 3. Agent X submits. `FindAsync` loads the row **as it is now**, so the tracked original value is B. 4. `SetValues(dto)` copies `dto.Version` into the **current** value. For a row version that value is never written, and it is not what the `WHERE` uses. 5. The `UPDATE` checks for B, which is still in the database, so it succeeds and Y's work is overwritten. The token was present, configured and loaded, and it still protected nothing, because the comparison ran against a version the user never saw. ## The fix After applying the posted values, restore the posted version as the original: ```csharp db.Entry(ticket).Property(t => t.Version).OriginalValue = dto.Version; ``` Now the `WHERE` carries A, the database holds B, zero rows are affected and EF Core throws `DbUpdateConcurrencyException`. This is the same pattern the ASP.NET Core Razor Pages concurrency tutorial uses. ## How each update style behaves | Update style | Original value of the token | Conflict detected? | |---|---|---| | `FindAsync` + `SetValues(dto)` | freshly loaded value | **no**, unless you set `OriginalValue` | | `FindAsync` + `SetValues(dto)` + `OriginalValue = dto.Version` | posted value | yes | | `Update(ticketFromDto)` (no load) | posted value, because attaching makes original equal current | yes | | `Attach(ticketFromDto)` + `IsModified` on edited fields | posted value | yes | With `Update` or `Attach` the token also needs to be in the object you attach; a client that omits it sends the default value, which then never matches. ## Making the round trip reliable - **Send the token out.** Include `Version` in the GET response DTO (a `uint` from `xmin` serializes as a number; a SQL Server `byte[]` as Base64). - **Require it back.** Validate that the PUT carries it; a missing token silently disables the check. - **Or use HTTP preconditions.** Send the version as an `ETag` and require `If-Match` on updates; map a mismatch to `412 Precondition Failed`. - **Report conflicts.** Catch `DbUpdateConcurrencyException`, return `409 Conflict` with ProblemDetails and, ideally, the current database values so the client can show what changed. ## Why the bug survives testing Single-user tests never interleave two edits, and an integration test that loads, edits and saves in one context always sees matching versions. Only a test that saves a competing change **between** the GET and the PUT - two contexts, or two HTTP calls - catches it. Write that test for every endpoint that edits a versioned entity.

  • Why does db.Tickets.Update(ticketFromDto) detect the conflict without setting OriginalValue?
    `Update` attaches an object the context has never seen. With nothing loaded, EF Core takes the posted values as both current and original, so the token's original value is the posted version and goes into the `WHERE`. The catch is that it writes every column, and the client must send the token.
  • The client omits Version from the PUT body. What happens with each update style?
    With load-then-`SetValues` and no `OriginalValue` assignment, the save succeeds and the check is silently skipped. With `Update` or with `OriginalValue = dto.Version`, the default value `0` goes into the `WHERE`, which in practice never matches a real version, so every save fails. Validate that the token is present instead of relying on either outcome.

It is like a reviewer checking a contract against the copy on the shared drive instead of the copy the author actually edited: the edit always looks current, because the comparison is made against whatever is newest, not against what the author started from.

  • Copying the posted version into the entity's current value is enough for EF Core to check it.
  • Loading the row right before saving makes the concurrency check more accurate.
  • A concurrency token protects the edit even if the client never sends it back.
  • EF Core compares the posted DTO with the database automatically.
  • Integration tests that load and save in one context prove the conflict handling works.