Sub topic 18
Handling Concurrency Conflicts
Many apps have more than one user. Two people can open the same record at the same time, and both can try to change it. This chapter shows how EF Core notices when that happens and what you can do about it.
What a Concurrency Conflict Is
Concurrency means more than one thing happening at the same time. A concurrency conflict happens when two users change the same row and one change silently overwrites the other.
Here is an example. A shop sells a mug for $10.
- Alice loads the mug. She sees $10.
- Bob loads the mug. He also sees $10.
- Alice changes the price to $12 and saves.
- Bob changes the price to $15 and saves.
By default, EF Core sends Bob's update without checking anything. The price becomes $15, and Alice's change is lost. Nobody gets an error. This problem is called a lost update.
Optimistic Concurrency
There are two main ways to prevent lost updates.
- Pessimistic concurrency locks the row while one user edits it. Everyone else waits. This is safe, but it is slow and can block people for a long time.
- Optimistic concurrency uses no locks. It assumes conflicts are rare. When a save happens, it checks whether the row changed since it was loaded. If it did, the save fails.
EF Core supports optimistic concurrency out of the box. It is the usual choice for web apps.
Concurrency Tokens
A concurrency token is a property that EF Core checks before it updates or deletes a row. You mark the property, and EF Core does the checking for you.
When you save, EF Core puts the token's original value in the SQL WHERE clause. The original value is the value the property had when you loaded the row. The SQL looks roughly like this:
UPDATE Products SET Price = 15, Version = 1
WHERE Id = 1 AND Version = 0;If someone else already changed Version, no row matches the WHERE clause. The database reports that 0 rows changed. EF Core expected 1, so it throws a DbUpdateConcurrencyException. An exception is an error object that stops normal code flow until something catches it.
Marking a Token
You can mark a token in two ways. Both do the same thing.
With a data annotation:
[ConcurrencyCheck]
public int Version { get; set; }With the Fluent API, inside OnModelCreating:
modelBuilder.Entity<Product>()
.Property(p => p.Version)
.IsConcurrencyToken();With SQLite, you must change Version yourself on every update. Adding 1 each time is the simplest way.
A Complete Example
This program creates a conflict on purpose. It uses two separate DbContext objects to act as Alice and Bob. Each context keeps its own copy of the product, the same way two web requests would.
Put this in Program.cs in the project from the setup chapter. The project needs the Microsoft.EntityFrameworkCore.Sqlite package.
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
// Start with a fresh database containing one product.
using (var setup = new ShopContext())
{
await setup.Database.EnsureDeletedAsync();
await setup.Database.EnsureCreatedAsync();
setup.Products.Add(new Product { Name = "Mug", Price = 10m });
await setup.SaveChangesAsync();
}
using var alice = new ShopContext();
using var bob = new ShopContext();
// Both users load the same row.
var aliceMug = await alice.Products.SingleAsync(p => p.Name == "Mug");
var bobMug = await bob.Products.SingleAsync(p => p.Name == "Mug");
// Alice saves first.
aliceMug.Price = 12m;
aliceMug.Version++;
await alice.SaveChangesAsync();
Console.WriteLine("Alice saved price 12.");
// Bob tries to save a change based on old data.
bobMug.Price = 15m;
bobMug.Version++;
try
{
await bob.SaveChangesAsync();
Console.WriteLine("Bob saved price 15.");
}
catch (DbUpdateConcurrencyException)
{
Console.WriteLine("Bob's save failed: someone changed the mug first.");
}
using var check = new ShopContext();
var final = await check.Products.SingleAsync();
Console.WriteLine($"Final price: {final.Price}, version: {final.Version}");
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = "";
public decimal Price { get; set; }
[ConcurrencyCheck]
public int Version { get; set; }
}
public class ShopContext : DbContext
{
public DbSet<Product> Products => Set<Product>();
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite("Data Source=shop.db");
}Run it with dotnet run. The output is:
Alice saved price 12.
Bob's save failed: someone changed the mug first.
Final price: 12, version: 1Alice's change is safe. Bob got an error instead of silently overwriting her change.
Resolving a Conflict
Catching the exception is only the first step. Next you decide whose data wins. The exception has an Entries list. Each entry is one entity that failed to save.
| Strategy | What happens | When to use it |
|---|---|---|
| Database wins | Throw away your changes and reload the latest values. | When the user can simply try again. |
| Client wins | Keep your changes and overwrite the database. | When the latest edit should always win. |
| Ask the user | Show both versions and let a person choose. | When the data matters, such as prices or orders. |
Database Wins
ReloadAsync replaces the entity's values with the current values from the database. Your unsaved changes are gone.
catch (DbUpdateConcurrencyException ex)
{
foreach (var entry in ex.Entries)
{
await entry.ReloadAsync();
}
}Client Wins
To keep your changes, tell EF Core that the database's current values are now the original values. Then the WHERE clause will match on the next save. You also need to bump Version again, starting from the database's number.
catch (DbUpdateConcurrencyException ex)
{
foreach (var entry in ex.Entries)
{
var dbValues = await entry.GetDatabaseValuesAsync();
if (dbValues == null)
{
Console.WriteLine("The row was deleted by another user.");
continue;
}
entry.OriginalValues.SetValues(dbValues);
var product = (Product)entry.Entity;
product.Version = dbValues.GetValue<int>(nameof(Product.Version)) + 1;
}
await bob.SaveChangesAsync();
}GetDatabaseValuesAsync returns null if another user deleted the row. Always check for that case.
Ask the User
For this strategy, read three sets of values from each entry:
entry.CurrentValues: what this user typed.entry.OriginalValues: what this user first loaded.await entry.GetDatabaseValuesAsync(): what is in the database now.
Show them to the person, let them pick, then use the client wins code to save their choice.
Common Mistakes
- Forgetting to change the token. With a manual counter, if you never increment
Version, the first writer won't update it, and later writers won't see a conflict. - Treating the exception as a crash. A conflict is normal in a multi-user app. Catch it and handle it.
- Using one context for both users. One context holds a single copy of each row, so it cannot produce a conflict with itself. Conflicts come from separate contexts, usually separate requests.
- Bulk methods skip the check.
ExecuteUpdateAsyncandExecuteDeleteAsyncdo not use concurrency tokens automatically. Add the token to yourWherefilter yourself if you need the check.
Exercise
Alice and Bob both load a product with Version 3. Alice saves first. Which Version value does EF Core put in the WHERE clause of Bob's UPDATE, and why does his save fail?
Show answer
EF Core uses Bob's original value, 3, so the SQL says WHERE Version = 3. Alice's save already changed Version to 4, so no row matches. The database reports 0 rows changed, and EF Core throws DbUpdateConcurrencyException.
Exercise
Change the catch block in the complete example so that Bob's price of 15 wins. What final price and version should the program print?
Show answer
Inside the catch block, loop over ex.Entries. Call GetDatabaseValuesAsync, pass the result to entry.OriginalValues.SetValues, set Version to the database Version plus 1, then call bob.SaveChangesAsync() again. The database Version was 1 after Alice's save, so the program prints "Final price: 15, version: 2".
Exercise
You use SQL Server. Which attribute and property type let the database update the concurrency token for you?
Show answer
Use [Timestamp] on a byte[] property, such as public byte[] RowVersion { get; set; }. SQL Server stores it as a rowversion column and changes it automatically on every update, so your code never sets it.