CodingNeed.

Production engineering workshop · 50 MIN

ASP.NET Core · Detect conflicting edits with a version token

A read-modify-write operation needs a conflict policy.

Optimistic concurrency includes the version observed by the client in the UPDATE predicate. EF Core compares the configured concurrency token’s original value. A changed row affects zero records and causes DbUpdateConcurrencyException. Scope reads by authenticated owner and use an application-managed version token when the database does not provide SQL Server rowversion. The surrounding authentication and DbContext registration belong in the host application.

First reproduce the normal path. Then force a failure at each boundary and inspect what remains true.

Read the example

// Entity configuration:
// modelBuilder.Entity<Note>().Property(n => n.Version).IsConcurrencyToken();
record EditNote(string Text, Guid Version);

app.MapPut("/notes/{id:guid}", async (Guid id, EditNote input,
    ClaimsPrincipal principal, AppDbContext db, CancellationToken ct) => {
  var owner = principal.FindFirstValue(ClaimTypes.NameIdentifier);
  if (owner is null) return Results.Unauthorized();
  if (string.IsNullOrWhiteSpace(input.Text) || input.Text.Length > 4000)
    return Results.BadRequest();
  var note = await db.Notes.SingleOrDefaultAsync(n => n.Id == id && n.OwnerId == owner, ct);
  if (note is null) return Results.NotFound();
  if (note.Version != input.Version) return Results.Conflict();
  note.Text = input.Text.Trim();
  note.Version = Guid.NewGuid();
  try { await db.SaveChangesAsync(ct); }
  catch (DbUpdateConcurrencyException) { return Results.Conflict(); }
  return Results.Ok(new {note.Id,note.Text,note.Version});
}).RequireAuthorization();
// Cookie-authenticated endpoints also need an antiforgery policy.
// Required imports include EF Core and System.Security.Claims.
Check the expected output
Review the behavior in the stated project environment.

Your challenge

Add a Guid Version property configured with IsConcurrencyToken to your Note entity. Wire this handler into an authenticated ASP.NET Core project. Simulate two clients reading the same version; only the first update should succeed. Add a test for cross-user access.

Solution cost: Indexed lookup and update; contention determines retries. time · One tracked entity per request. space

Common trap

An application-only version comparison is insufficient; the database UPDATE must also include the original token.

Study the project implementation
// Entity configuration:
// modelBuilder.Entity<Note>().Property(n => n.Version).IsConcurrencyToken();
record EditNote(string Text, Guid Version);

app.MapPut("/notes/{id:guid}", async (Guid id, EditNote input,
    ClaimsPrincipal principal, AppDbContext db, CancellationToken ct) => {
  var owner = principal.FindFirstValue(ClaimTypes.NameIdentifier);
  if (owner is null) return Results.Unauthorized();
  if (string.IsNullOrWhiteSpace(input.Text) || input.Text.Length > 4000)
    return Results.BadRequest();
  var note = await db.Notes.SingleOrDefaultAsync(n => n.Id == id && n.OwnerId == owner, ct);
  if (note is null) return Results.NotFound();
  if (note.Version != input.Version) return Results.Conflict();
  note.Text = input.Text.Trim();
  note.Version = Guid.NewGuid();
  try { await db.SaveChangesAsync(ct); }
  catch (DbUpdateConcurrencyException) { return Results.Conflict(); }
  return Results.Ok(new {note.Id,note.Text,note.Version});
}).RequireAuthorization();
// Cookie-authenticated endpoints also need an antiforgery policy.
// Required imports include EF Core and System.Security.Claims.

Further reading: Official documentation

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.