skip to content

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

level: seniorimportance: should knowfreq 40%

answer

  1. ex.Entries
  2. CurrentValues, OriginalValues, GetDatabaseValuesAsync
  3. null database values: row deleted
  4. OriginalValues.SetValues(databaseValues)
  5. ReloadAsync for store wins

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.

solid answer

~40 s

`DbUpdateConcurrencyException.Entries` gives the conflicting `EntityEntry` objects. For each one, `CurrentValues` is what you tried to write, `OriginalValues` is what you loaded, and `await entry.GetDatabaseValuesAsync()` is what the database holds now - `null` if the row was deleted, which needs its own handling. Then pick a policy: **store wins** - `await entry.ReloadAsync()` and drop your edit; **client wins** - `entry.OriginalValues.SetValues(databaseValues)` and save again, overwriting the other change; or **merge** - per property, keep yours where only you changed it, take theirs where only they did, and ask a person where both did. Every path that saves again must refresh the original values, or the token still mismatches. Loop, because a third writer can win in between, and cap the attempts.

code

csharp · 14 lines
csharp
static void Merge(PropertyValues current, PropertyValues original, PropertyValues database)
{
    foreach (var property in current.Properties)
    {
        var mine = current[property];
        var theirs = database[property];
        var start = original[property];

        if (Equals(mine, start) && !Equals(theirs, start))
            current[property] = theirs;          // only they changed it
        // only I changed it: keep mine
        // both changed it: a business rule or the user decides
    }
}

go deeper

for a junior

Know that EF Core exposes the value you wrote, the value you loaded and the value in the database for a conflicting entity.

for a middle

Implement store wins with ReloadAsync and client wins with OriginalValues.SetValues, and handle a null database value.

for a senior

Write a property-level merge with a bounded retry loop, and decide which conflicts code may resolve and which must go back to a person.

for a principal

Define per aggregate whether conflicts are auto-merged, last-writer-wins or user-resolved, and how that is visible in the product.

## Three sets of values When `SaveChanges` throws `DbUpdateConcurrencyException`, the exception's `Entries` property lists the `EntityEntry` of each entity whose `UPDATE` or `DELETE` affected no row. Each entry gives you three snapshots of the same row: | Value set | API | Meaning | |---|---|---| | **Current** | `entry.CurrentValues` | what your code tried to write | | **Original** | `entry.OriginalValues` | what was loaded (or restored) before the edit; its token value went into the `WHERE` | | **Database** | `await entry.GetDatabaseValuesAsync()` | what the database holds right now - `null` if the row no longer exists | All three are `PropertyValues` objects: index them by property (`values[property]` or `values["Status"]`), enumerate `values.Properties`, copy them with `SetValues`, or build an entity with `ToObject()`. ## Choosing a policy Two helpdesk agents edit ticket 4711. Agent A changed `Priority`; agent B, whose save failed, changed `Status`. 1. **Tell the user** (the default for interactive edits): return `409 Conflict` with the database values and let the agent decide. 2. **Store wins**: `await entry.ReloadAsync()` overwrites current and original values with the database values and leaves the entity `Unchanged`. B's edit is discarded. 3. **Client wins**: `entry.OriginalValues.SetValues(databaseValues)` and save again. The original token now matches the database, so B's `UPDATE` succeeds - and overwrites A's `Priority` too if B's entity marks it modified. 4. **Merge**: for each property, compare the three values: - only you changed it (current != original, database == original): keep yours; - only they changed it (database != original, current == original): take theirs into the current value; - both changed it: a business rule or a person decides. Then refresh the originals from the database values and save again. In every path that saves again, **refreshing the original values is what makes the retry possible**: until the original token equals the database token, the `WHERE` keeps matching nothing. ## The deleted-row case `GetDatabaseValuesAsync()` returns `null` when the row is gone. Reloading such an entry detaches the entity. Decide explicitly: report "the ticket was deleted", re-insert it as new, or drop the edit. Code that dereferences the database values without a null check turns a conflict into a `NullReferenceException`. ## A loop with a limit ```csharp for (var attempt = 1; ; attempt++) { try { await db.SaveChangesAsync(ct); break; } catch (DbUpdateConcurrencyException ex) when (attempt < 3) { foreach (var entry in ex.Entries) { var database = await entry.GetDatabaseValuesAsync(ct) ?? throw new InvalidOperationException("The ticket was deleted by another agent."); Merge(entry.CurrentValues, entry.OriginalValues, database); entry.OriginalValues.SetValues(database); // token now matches } } } ``` A third writer can win between your read of the database values and your retry, so loop - but cap the attempts and then surface the conflict instead of spinning. ## Related tools - **`ISaveChangesInterceptor.ThrowingConcurrencyException`** (and its async twin) runs just before EF Core throws, and can suppress the exception - useful for a policy such as "deleting an already-deleted row is fine". - **Execution strategies do not retry concurrency conflicts**: a conflict is a business outcome, not a transient fault. - **`ExecuteUpdateAsync` does not apply tokens**, so set-based updates need the token in their own `Where` if they must respect it.

  • You set the current values to the database values but forget OriginalValues.SetValues. Why does the retry fail again?
    The `WHERE` uses the token's original value, which is still the stale one you loaded. Changing current values does not touch it, so the retried `UPDATE` again matches no row. Refresh the original values from the database values before saving again.
  • When is ReloadAsync the right answer, and what does it do to the edit?
    When the database's version should win - for example, a background job's derived update that can be recomputed. `ReloadAsync` overwrites current and original values with the database values and leaves the entity `Unchanged`, so the job's edit is discarded; recompute and save again if needed. If the row is gone, the entity ends up detached.

Resolving a conflict is like merging two edited copies of a document against the version both started from: lines only one person touched merge automatically, lines both touched need a human, and you note which version you merged against before saving again.

  • GetDatabaseValuesAsync always returns values, even for a deleted row.
  • Setting the current values is enough for the retried UPDATE to succeed.
  • EnableRetryOnFailure retries concurrency conflicts automatically.
  • Client wins means calling ReloadAsync and saving again.
  • One retry always succeeds, so no loop or limit is needed.