Entity Framework Core Advanced

Handling concurrency conflicts

When two users edit the same record at the same time, the last save silently wins and the first user's change is lost. This lesson shows optimistic concurrency with a rowversion token, how EF Core detects the conflict, and how to resolve it in an MVC app.

Detecting a conflict
  1. StartBoth users readProduct 7 with RowVersion A
  2. Step 2Asha savesRow updated; RowVersion becomes B
  3. Step 3Ravi savesWHERE RowVersion = A matches 0 rows
  4. Step 4ExceptionDbUpdateConcurrencyException is thrown
  5. EndResolveShow current values and let Ravi decide

The lost update problem

Asha and Ravi both open product 7 with price 500. Asha saves 450. A minute later Ravi saves the stock count, but his form still holds price 500, so his save puts the old price back. Nobody sees an error.

Optimistic concurrency does not lock anything. It checks at save time whether the row changed since you read it, and fails if it did.

Adding a concurrency token

In SQL Server a rowversion column changes automatically on every update. EF Core adds it to the WHERE clause of each UPDATE and DELETE; if no row matches, someone else changed it.

C#
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public decimal Price { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; } = [];
}

// SQL sent by SaveChanges:
// UPDATE Products SET Price = @p0
// WHERE Id = @p1 AND RowVersion = @p2;   -- 0 rows => conflict

Handling the conflict in MVC

Send RowVersion to the form as a hidden field so the original value comes back with the post. Catch DbUpdateConcurrencyException and show the user what changed.

C#
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, ProductEdit input)
{
    var product = await db.Products.FindAsync(id);
    if (product is null) return NotFound();

    db.Entry(product).Property(p => p.RowVersion).OriginalValue = input.RowVersion;
    product.Price = input.Price;

    try
    {
        await db.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    catch (DbUpdateConcurrencyException ex)
    {
        var current = await ex.Entries.Single().GetDatabaseValuesAsync();
        if (current is null) return NotFound();   // deleted meanwhile
        ModelState.AddModelError("", $"Someone changed this product. Current price: {current["Price"]}. Save again to overwrite.");
        input.RowVersion = (byte[])current["RowVersion"]!;
        return View(input);
    }
}

Options for resolving

  • Client wins: reload the database values as original values and save again.
  • Database wins: discard the user's change and show the current data.
  • Merge: show both versions and let the user decide (best for important data).
  • For counters such as stock, use an atomic update (ExecuteUpdate with Stock - 1) instead of read-modify-write.

Interview question

What is optimistic concurrency and how does EF Core implement it?

Optimistic concurrency assumes conflicts are rare, so it takes no locks while a user edits and checks for changes only when saving. EF Core includes a concurrency token, typically a SQL Server rowversion column marked [Timestamp], in the WHERE clause of UPDATE and DELETE. If no row matches because someone changed it, SaveChanges throws DbUpdateConcurrencyException for the app to resolve.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.