简体   繁体   English

实体框架并发根据现有值增加一个字段值1

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

I need to count when users submitting a web form. 我需要计算用户提交Web表单的时间。 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 您还可以向您的实体添加行版本字段以使EF支持开放式并发: 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 如果并发更新,则可以捕获DbUpdateConcurrencyException,重新加载实体并再次增加计数器,如下所示: https ://msdn.microsoft.com/zh-cn/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. 它比线程同步容易得多,并且适用于多个IIS配置。

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). 其他选项可能是您更改了架构,因此最终您不需要将总计数保存在数据库中,但是您可以使用Count方法(例如,聚合)进行计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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