Explain optimistic concurrency in Entity Framework Core and how you would present conflicts to a React user.
Razorpay · Full Stack Developer · 3-4-years · technical
Published
Year not specified · .NET, Entity Framework Core, React
Community answers
Posted by wasAsked editorial collection
Add an EF Core concurrency token such as rowversion. EF includes the original token in UPDATE/DELETE; if another writer changed the row, zero rows are affected and SaveChanges throws DbUpdateConcurrencyException.
Example:
public class Product {
[Timestamp] public byte[] Version { get; set; } = [];
}
Return the token to the client (often as an ETag) and require it on updates. On conflict, reload current values and either reject with 409/412, merge explicitly, or retry only when the operation is safe. Never blindly overwrite. Tenant predicates must also include authenticated RestaurantId and OutletId. Test two contexts updating the same row so the conflict path is proven.
Backbencher Developer · · 0 likes
Optimistic concurrency assumes conflicts are rare. Instead of locking rows, EF Core checks at save time that the row has not changed since it was read.
Setting it up:
public class Product
{
public int Id { get; set; }
public decimal Price { get; set; }
[Timestamp] public byte[] RowVersion { get; set; } = []; // SQL Server rowversion
}
When SaveChanges runs, EF adds the original value to the WHERE clause:
UPDATE Products SET Price = @p WHERE Id = @id AND RowVersion = @originalVersion
If another user changed the row, zero rows are affected and EF throws DbUpdateConcurrencyException. Other databases use a version or concurrency token column ([ConcurrencyCheck] or IsConcurrencyToken, or xmin in PostgreSQL).
Web API flow:
- Return the version with the resource, ideally as an ETag header (base64 of RowVersion) or a field in the DTO.
- The client sends it back with the update (If-Match header or body field).
- The API sets the original value: db.Entry(product).Property(p => p.RowVersion).OriginalValue = clientVersion;
- On DbUpdateConcurrencyException, return 409 Conflict (or 412 Precondition Failed when using If-Match), including the current server values.
Presenting the conflict in React:
- Show a clear message: "This product was changed by someone else while you were editing."
- Show the differences: their value vs your value for each field that changed.
- Offer choices: reload and discard my changes, keep my changes and overwrite (resubmit with the new version), or merge field by field.
- Keep the user's unsaved input so nothing is lost.
- For collaborative screens, reduce conflicts by refreshing data periodically or showing "edited by X" indicators.
When to prefer pessimistic locking instead: very high contention on the same rows, or operations where retrying is expensive. For most business forms, optimistic concurrency is simpler and scales better.