How do you handle optimistic concurrency conflicts in EF Core using a concurrency token (like RowVersion)?
Short answer
Marking a property with [ConcurrencyCheck] or, more commonly, using a dedicated [Timestamp]/RowVersion byte[] column, causes EF Core to include that column's original value in the WHERE clause of UPDATE/DELETE statements -- if another process modified the row in the meantime…
Advertisement
AModel answer
Marking a property with [ConcurrencyCheck] or, more commonly, using a dedicated [Timestamp]/RowVersion byte[] column, causes EF Core to include that column's original value in the WHERE clause of UPDATE/DELETE statements -- if another process modified the row in the meantime (changing the RowVersion), zero rows match, and EF Core throws a DbUpdateConcurrencyException, letting your application detect and handle the conflict (e.g., by reloading and asking the user to retry) instead of silently overwriting someone else's concurrent changes.
public class Product {
public int Id { get; set; }
public decimal Price { get; set; }
[Timestamp] public byte[] RowVersion { get; set; }
}
try {
await context.SaveChangesAsync();
} catch (DbUpdateConcurrencyException) {
// Another user modified this row concurrently -- reload and prompt for resolution
}Real-world example
An inventory management system uses RowVersion-based concurrency tokens on stock quantities so that two warehouse staff simultaneously updating the same product's count get a clear conflict error instead of one person's update silently overwriting the other's.
Likely follow-ups
- What's the difference between optimistic and pessimistic concurrency control?
- How do you resolve a DbUpdateConcurrencyException programmatically (client-wins vs store-wins)?
Related topics