Asp.net mvc 4 使用EntityFramework5和MVC4从表中读取、推断计数器并插入数据库
我有这种情况。我有一张叫“请求”的桌子。此表有一个名为Number的列。每次我想插入一个新的请求,然后我获取最后一个请求,并根据它的请求号推断出一个新的请求。 例如,我在我的数据库Request1上有一个编号0001,然后当我插入一个新的时,我获取Request1,并根据其编号推断出我的新请求编号,该编号应为0002 当我想同时创建两个请求时,就会出现问题。进程1获取Request1,进程2也获取Request1。当进程1推断出新的请求号(应该是0001)时,进程2也会这样做。最后,我将创建两个相同编号的新请求 有人知道怎么解决这个问题吗Asp.net mvc 4 使用EntityFramework5和MVC4从表中读取、推断计数器并插入数据库,asp.net-mvc-4,concurrency,entity-framework-5,Asp.net Mvc 4,Concurrency,Entity Framework 5,我有这种情况。我有一张叫“请求”的桌子。此表有一个名为Number的列。每次我想插入一个新的请求,然后我获取最后一个请求,并根据它的请求号推断出一个新的请求。 例如,我在我的数据库Request1上有一个编号0001,然后当我插入一个新的时,我获取Request1,并根据其编号推断出我的新请求编号,该编号应为0002 当我想同时创建两个请求时,就会出现问题。进程1获取Request1,进程2也获取Request1。当进程1推断出新的请求号(应该是0001)时,进程2也会这样做。最后,我将创建两个
对不起我的英语 有几种方法可以解决你的问题
- 字段始终是数字、连续的,并且每个记录的值必须高于上一个记录李>
// Probably you have this kind of code (which fieldID should be the field name)
public Int32 fieldID {get; set;}
// Just add these two attributes before the declaration of the field
[Key]
[DatabaseGenerated (DatabaseGeneratedOption.Identity)]
public Int32 fieldID {get; set;}
/* Example in C#, assuming you are using SQL Server and EFCF */
/* EF CF means Entity Framework Code First! */
- 您需要实现一个逻辑来填充此字段,这可能与上面描述的不同,或者该字段不是数字字段,或者不能由数据库完成,并且必须由您的应用程序直接完成李>
锁定
在处理数据的类中,您遇到了以下问题:声明一个Object类型的变量,静态且只读,如下所示:
private static readonly Object concurrencyLock=new Object()代码>
在实现需要唯一访问的逻辑的方法中,使用锁策略封装代码
lock(concurrencyLock) {
//Do stuff here without concurrency
/* When the current request into this part of the code,
any other request will execute until the line above with "lock" statement.
Until this current request exit this "lock" block of code,
the other(s) will wait. As this one leave this block, one other join...
One at a time as you wish. */
}
也有其他方法可以做到这一点,但有点复杂,或者在Web应用程序中不能很好地工作(例如互斥,如果它是Windows服务或Windows窗体应用程序,则可以很好地工作)可能与