skip to content

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

level: juniorimportance: should knowfreq 45%

answer

  1. rows affected versus rows expected
  2. UPDATE or DELETE, not INSERT
  3. derives from DbUpdateException
  4. a row deleted by someone else
  5. Entries name the losing entities

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.

solid answer

~40 s

EF Core expects every `UPDATE` and `DELETE` it sends to affect exactly one row. When the database reports zero, `SaveChanges` throws `DbUpdateConcurrencyException`, whose message says the operation "was expected to affect 1 row(s), but actually affected 0 row(s)". That happens when a concurrency token in the `WHERE` clause no longer matches - another helpdesk agent saved the ticket first - or when the row was deleted meanwhile, even with no token configured. It derives from `DbUpdateException`, so catch it first. Inserts do not raise it: a duplicate key or any other constraint violation is the provider's exception (for Npgsql a `PostgresException`) wrapped in a plain `DbUpdateException`. In both cases `Entries` lists the entities involved.

code

csharp · 14 lines
csharp
try
{
    await db.SaveChangesAsync(ct);
    return Results.NoContent();
}
catch (DbUpdateConcurrencyException ex)        // must come first
{
    var ticket = (Ticket)ex.Entries.Single().Entity;
    return Results.Conflict($"Ticket {ticket.Id} was changed by someone else.");
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: PostgresErrorCodes.UniqueViolation })
{
    return Results.Conflict("A ticket with that reference already exists.");
}

go deeper

for a junior

Know that DbUpdateConcurrencyException means an update or delete hit no row, and that it is a kind of DbUpdateException.

for a middle

Explain the rows-affected check, the deleted-row case without a token, and why inserts report constraint errors instead.

for a senior

Map the two exceptions to distinct HTTP outcomes and use Entries to decide what the client should reload.

for a principal

Decide which entities in a model are worth guarding with tokens and what the product does when two users collide.

## Two exceptions from one call `SaveChanges` and `SaveChangesAsync` report write failures with two related exception types in the `Microsoft.EntityFrameworkCore` namespace: - **`DbUpdateException`** - something went wrong while the database executed a command: a foreign key, unique, check or not-null constraint failed, a value did not fit, the connection broke. The provider's own exception sits in `InnerException`. - **`DbUpdateConcurrencyException`** - a subclass of `DbUpdateException` meaning "the command ran, but it did not touch the row EF Core expected it to touch". Because one derives from the other, a `catch (DbUpdateException)` also catches concurrency failures; put the `catch (DbUpdateConcurrencyException)` block first. ## How EF Core decides it was a concurrency failure For every entity it updates or deletes, EF Core sends one statement whose `WHERE` clause names the row by its key - plus any **concurrency token** configured on the entity. It then checks the number of rows each statement affected: 1. Expected one row, got one: success. 2. Expected one row, got zero: EF Core throws `DbUpdateConcurrencyException` with the message "The database operation was expected to affect 1 row(s), but actually affected 0 row(s); data may have been modified or deleted since entities were loaded." Zero rows can mean two different things: - **A token mismatch.** Two helpdesk agents open ticket 4711. Agent A saves first, which changes the ticket's row version. Agent B's `UPDATE ... WHERE "Id" = 4711 AND "xmin" = @original` now matches nothing. - **A deleted row.** Someone closed and purged the ticket. Agent B's `UPDATE ... WHERE "Id" = 4711` matches nothing - this happens **even with no concurrency token**, because the key alone no longer finds a row. ## What does not raise it | Situation | Exception | |---|---| | `UPDATE` / `DELETE` affects zero rows | `DbUpdateConcurrencyException` | | `INSERT` with a duplicate primary key or unique value | `DbUpdateException` wrapping the provider's exception | | a foreign key points at a missing row | `DbUpdateException` | | the connection breaks while the batch runs | `DbUpdateException` wrapping the provider's exception (a retrying execution strategy may retry it first) | Without a token, a plain update of a row that still exists **always succeeds**: the last writer silently wins. Detecting that case is what concurrency tokens are for. ## What the exception gives you - `Entries` - the `EntityEntry` objects whose commands failed, so you can tell which ticket conflicted. - Through each entry: `CurrentValues` (what you tried to write), `OriginalValues` (what you loaded) and `GetDatabaseValuesAsync()` (what is there now, or `null` if the row is gone). - The change tracker is untouched: the entries keep their pending states, and nothing from the failed save is accepted. In a Web API the usual minimum is to map the exception to an HTTP `409 Conflict` ProblemDetails response and let the client reload. Resolving the conflict in code - merging, store wins, client wins - is a separate decision built on those three value sets. ## Mistakes - Catching `DbUpdateException` first and never reaching the concurrency handler. - Expecting a duplicate insert to be reported as a concurrency conflict. - Assuming that without a token EF Core can never throw this exception. - Assuming the exception means EF Core locked the row; EF Core's optimistic concurrency takes no locks.

  • Can EF Core throw DbUpdateConcurrencyException for an entity with no concurrency token at all?
    Yes. Every `UPDATE` and `DELETE` is expected to affect one row; if the row was deleted after you loaded it, the key-only `WHERE` matches nothing and EF Core throws it. What a token adds is detection of a row that still exists but was changed.
  • Why does a catch (DbUpdateException) block placed before catch (DbUpdateConcurrencyException) break conflict handling?
    `DbUpdateConcurrencyException` derives from `DbUpdateException`, so the first block matches it and the later, more specific block is never reached. The C# compiler rejects that order outright, which is a useful hint that the specific type must come first.

  • Inserting a duplicate primary key throws DbUpdateConcurrencyException.
  • Without a concurrency token EF Core can never throw DbUpdateConcurrencyException.
  • DbUpdateConcurrencyException and DbUpdateException are unrelated, so catch order does not matter.
  • EF Core locks the row when it loads it, and the exception means the lock was lost.
  • After the exception the change tracker marks the entity Unchanged.