Entity Framework Core Interview Question #120

How do you handle DbUpdateConcurrencyException?

Change Tracking, Updates, Transactions & Concurrency Mid-Level Intermediate

Quick Interview Answer

Catch DbUpdateConcurrencyException around SaveChanges when the application uses optimistic concurrency. Inspect the affected entries and retrieve current database values if needed.

Detailed Explanation

Catch DbUpdateConcurrencyException around SaveChanges when the application uses optimistic concurrency. Inspect the affected entries and retrieve current database values if needed.

The correct resolution is a business decision: inform the user, reload the latest values, merge non-conflicting changes, or retry after updating original values.

Do not automatically overwrite another user's changes unless that behavior is explicitly intended.

Code Example

try
{
    await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException ex)
{
    var entry = ex.Entries.Single();
    var databaseValues =
        await entry.GetDatabaseValuesAsync();

    // Decide: reload, merge, reject, or retry.
    throw;
}