skip to content

RowVersion & Conflict Handling

Optimistic concurrency in EF Core: concurrency tokens, row versions, DbUpdateConcurrencyException and resolving the conflict. Interviewers ask how a lost update is caught when two users edit a row.

part ofEntity Framework Coreread it →
on this pageshow

explore

questions

5

In EF Core 10, how does [ConcurrencyCheck] or IsConcurrencyToken differ from [Timestamp] or IsRowVersion, and what does each add to an UPDATE?

level: middleimportance: must knowfreq 62%

answer

  1. both add the original value to WHERE
  2. who changes the value
  3. ValueGeneratedOnAddOrUpdate plus concurrency token
  4. application-managed GUID or counter
  5. SQL Server rowversion, PostgreSQL xmin

basics

~20 s

Both put the property's original value into the WHERE of every UPDATE and DELETE. [ConcurrencyCheck] / IsConcurrencyToken leaves changing it to your code; [Timestamp] / IsRowVersion also marks it generated on add and update, so the database bumps it.

solid answer

~40 s

A **concurrency token** is any property whose original value EF Core adds to the `WHERE` of the `UPDATE` and `DELETE` it sends: `UPDATE "Tickets" SET "Status" = @p0 WHERE "Id" = @p1 AND "Version" = @p2`. `[ConcurrencyCheck]` and `IsConcurrencyToken()` do only that. The value never changes unless your code changes it - typically `ticket.Version = Guid.NewGuid()` on each save, perhaps in an interceptor - and a token nobody changes never detects a conflict. `[Timestamp]` and `IsRowVersion()` do the same and also configure `ValueGeneratedOnAddOrUpdate`: the database generates a new value on every insert and update, EF Core never writes it and reads the new value back after saving. The provider decides what that maps to - a SQL Server `rowversion`, or PostgreSQL's `xmin` for a `uint` with Npgsql.

code

csharp · 13 lines
csharp
public class Ticket
{
    public int Id { get; set; }
    public string Status { get; set; } = "Open";

    [ConcurrencyCheck]                 // application-managed
    public Guid Version { get; set; }
}

// on every save that should count as a new version
ticket.Status = "Waiting on customer";
ticket.Version = Guid.NewGuid();
await db.SaveChangesAsync(ct);   // WHERE "Id" = @id AND "Version" = @originalVersion

go deeper

for a junior

Recognise [ConcurrencyCheck] and [Timestamp] as the two ways to mark a concurrency token.

for a middle

Show the WHERE clause EF Core generates and explain who changes the value for each kind of token.

for a senior

Choose between a row version and an application-managed token per provider, and avoid tokens nobody bumps.

for a principal

Set a model-wide convention for concurrency tokens that survives provider changes and makes unprotected aggregates visible.

## What a concurrency token is EF Core uses **optimistic concurrency**: it takes no locks, and instead makes a write fail if the row changed since it was read. The mechanism is a **concurrency token** - a property whose **original value** (the value loaded from the database) is added to the `WHERE` clause of every `UPDATE` and `DELETE` for that entity. If another writer changed the token in the meantime, the statement matches no row and `SaveChanges` throws `DbUpdateConcurrencyException`. In a helpdesk, two agents edit ticket 4711. With a `Version` token loaded as `v1`, agent B's save sends: ```sql UPDATE "Tickets" SET "Status" = @p0 WHERE "Id" = @p1 AND "Version" = @p2; -- @p2 = v1 ``` If agent A's save already moved the row to `v2`, zero rows are affected. ## Two ways to declare a token | | `[ConcurrencyCheck]` / `IsConcurrencyToken()` | `[Timestamp]` / `IsRowVersion()` | |---|---|---| | Adds original value to `WHERE` | yes | yes | | Value generated by | your code | the database, on insert and update | | EF Core writes the column | yes, when you change it | never; it reads the new value back after the save | | Typical types | `Guid`, `int` counter, or any business column | SQL Server `rowversion` (`byte[]`, or `long`/`ulong` since EF Core 8); a `uint` mapped to PostgreSQL's `xmin` with Npgsql | | Works on databases with no auto-updating type | yes | only where the provider maps one | Under the hood `IsRowVersion()` is exactly `ValueGeneratedOnAddOrUpdate()` plus `IsConcurrencyToken()`; the `[Timestamp]` attribute applies the same two settings. Both attributes live in `System.ComponentModel.DataAnnotations`. ## Application-managed tokens With `[ConcurrencyCheck]` the database knows nothing special about the column. That has consequences: 1. **You must change it on every save that should count as a new version.** If no code updates `Version`, every later `UPDATE` still matches, and conflicts are never detected. 2. You choose **which edits bump the version**: a change to a cached `ViewCount` column need not conflict with an agent's reply. 3. A common pattern is assigning `Guid.NewGuid()` in a `SaveChanges` interceptor for every `Modified` entity of the type. 4. You can also mark an ordinary business column, such as `Status`, as a token; then only concurrent changes to that column conflict. ## Database-generated row versions With `[Timestamp]` / `IsRowVersion()` the provider maps the property to something the database changes on every write: - **SQL Server:** a `rowversion` column, exposed as `byte[]` by default; EF Core 8 added mapping it to `long` or `ulong`. - **PostgreSQL with Npgsql:** a `uint` property configured as a row version maps to the system column `xmin`, which PostgreSQL changes on every row update; migrations do not create it. - **SQLite:** no auto-updating type exists, so use an application-managed token or a trigger. Because the value is store-generated, EF Core never includes it in the `SET` list; it reads the new value back after each save, so the tracked entity is ready for the next one. ## Choosing - Prefer a **row version** when the provider has one: every write to the row is protected, with no code to forget. - Use **`[ConcurrencyCheck]`** when the database has no such type, when only some columns should conflict, or when the token must be portable across providers. - Either way, a token only helps if its **original value is the one the user saw** - after a round trip through a client that means restoring it as the original value before saving.

  • A [ConcurrencyCheck] Guid Version property never raises conflicts, even when two agents clearly overwrite each other. What is missing?
    Nothing changes the token. EF Core compares the original value with the database value, but if no code assigns a new `Version` on save, the database value never moves and every `UPDATE` matches. Assign `Guid.NewGuid()` on each relevant save - by hand or in a `SaveChanges` interceptor - or switch to a database-generated row version.
  • Why does EF Core never put a [Timestamp] property in the SET list of an UPDATE?
    Row versions are configured as generated on add and update, which makes EF Core ignore the property when saving and read the new value back afterwards. The database owns the value; sending one would be meaningless or, for SQL Server `rowversion`, rejected.

  • [ConcurrencyCheck] makes the database change the column on every update.
  • A concurrency token makes EF Core lock the row until SaveChanges completes.
  • EF Core compares the token's current value, not its original value, in the WHERE clause.
  • [Timestamp] works the same on every database, SQLite included.
  • EF Core writes a new [Timestamp] value into the SET list on each update.

Assumes EF Core 10; since EF Core 8 a SQL Server rowversion can map to long or ulong instead of only byte[].

open as a page

In EF Core 10, when does SaveChanges throw DbUpdateConcurrencyException rather than a plain DbUpdateException?

level: juniorimportance: should knowfreq 45%

basics

~20 s

DbUpdateConcurrencyException is thrown when an UPDATE or DELETE that SaveChanges sent affects no row - because a concurrency token no longer matched or the row is gone. Constraint violations, including a duplicate key on INSERT, surface as a plain DbUpdateException.

open as a page

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%

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.

open as a page

With EF Core 10 and the Npgsql provider, how do you use PostgreSQL's xmin column as an automatic row version for a Ticket entity?

level: middleimportance: should knowfreq 35%

basics

~20 s

Declare a uint property and configure it with [Timestamp] or IsRowVersion(). The Npgsql provider maps such a property to PostgreSQL's xmin system column of type xid, which changes on every row update, so no migration creates it.

open as a page

In EF Core 10, after catching DbUpdateConcurrencyException, how do you resolve the conflict using current, original and database values?

level: seniorimportance: should knowfreq 40%

basics

~20 s

For each entry in ex.Entries, compare CurrentValues (your edit), OriginalValues (what you loaded) and GetDatabaseValuesAsync() (what is there now, or null if deleted). Choose the values to keep, set OriginalValues from the database values so the token matches, and call SaveChanges again.

open as a page