How to avoid update conflict when updating the same record at the same time

asp.net c# entity-framework entity-framework-6 sql-server

Question

I'm designing an inventory system with Entity Framework and SQL Server. This app will be used by thousands of users. How do I design an app/database that will allow users to update the same inventory data at the same time? At the moment, for consistency, I use row versioning, but this often causes "Update conflict" errors.

1
1
5/28/2017 5:48:44 AM

Accepted Answer

Read more about Retry Pattern (here is my post about it). With it you can detect conflicts and make a desicion what to do (rewrite, merge or throw error to user).

Example of usage:

var retryCount = 3;
var currentRetry = 0;
using (var context = new DbContext(ConnectionString))
{
    var user = context.Set<User>().First(o => o.Id == 1);
    user.Login = "newuserlogin";
    do
    {
        try
        {
            currentRetry++;
            context.SaveChanges();
            break;
        }
        catch (DbUpdateConcurrencyException ex) when (currentRetry <= retryCount)
        {
            //conflict detected
            var entry = ex.Entries.Single();
            //rewrite values from database
            entry.OriginalValues.SetValues(entry.GetDatabaseValues());
        }
    } while (true);
}
1
8/9/2017 9:12:05 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow