Handling Entity Framework Core Concurrency Issues in .NET 6 with Optimistic Concurrency Control
I've tried everything I can think of but I'm sure I'm missing something obvious here, but This might be a silly question, but I'm building a web application using ASP.NET Core 6 with Entity Framework Core, and I'm facing a concurrency issue when two users try to update the same record at the same time... I have implemented optimistic concurrency control by adding a `RowVersion` property to my entity, but I still encounter an `DbUpdateConcurrencyException` when I try to save the changes. Here's the relevant part of my entity model: ```csharp public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } [Timestamp] public byte[] RowVersion { get; set; } } ``` In my update method, I retrieve the product using its ID and check for the `RowVersion` before saving: ```csharp public async Task<IActionResult> UpdateProduct(int id, Product updatedProduct) { var existingProduct = await _context.Products.FindAsync(id); if (existingProduct == null) { return NotFound(); } _context.Entry(existingProduct).OriginalValues["RowVersion"] = updatedProduct.RowVersion; existingProduct.Name = updatedProduct.Name; existingProduct.Price = updatedProduct.Price; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { return Conflict(); // Handling conflict } return NoContent(); } ``` When the `DbUpdateConcurrencyException` occurs, I would like to inform the user that their changes could not be saved due to another user updating the record. However, I noticed that the exception gets thrown even if the `RowVersion` is set correctly in the original values, leading to confusion. I've ensured that both users see the same `RowVersion` value when they retrieve the record. What am I missing here, and how can I correctly handle this concurrency situation and provide informative feedback to the users? My development environment is Windows. I'm working on a application that needs to handle this. How would you solve this? I'm developing on Ubuntu 22.04 with C#. Has anyone else encountered this? I'm coming from a different tech stack and learning C#. What's the best practice here?