简体   繁体   中英

Entity Framework concurrent issue a field value increase 1 according to the existing value

I need to count when users submitting a web form. I have encountered a concurrent problem when more then one user submit a form at the same time. some of counter value are the same. How to prevent?

var db = new MyDB();

var maxCounter = db.TableA.Where(x=>x.OrgId == 1).Max(x=>x.counter);

int newCounter = 0;
if(maxCounter != null)
{
    newCounter = maxCounter +1;
}

var newRecord = new TableA(){ OrgId = 1, counter = newCounter, createdDate = DateTime.Now, createdBy = username };
db.TableA.Add(newRecord);
db.SaveChanges();

You can also add a row version field to your entity to have EF support optimistic concurrency: http://www.codeproject.com/Articles/817432/Optimistic-Concurrency-in-Entity-Framework-Code-Fi

In case of concurrent updated, you can catch the DbUpdateConcurrencyException, reload the entity and increment the counter again, as seen here: https://msdn.microsoft.com/en-us/data/jj592904.aspx

You can log all form submits as separate records and aggregate it when necessary. It's much easier than thread synchronization and applicable in multiple IIS configuration.

You need to use lock around the code that does update the table, but this may cause performance issue.

Other option maybe you change your schema so eventually you don't need to save the total count in the data base, but you can calculated it using Count method for example (aggregation).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM