我使用 Entity Framework 从不同应用程序调用同一数据库。但是,当一个应用程序正在读取/更新记录时,我不希望其他应用程序读取该数据。
我尝试使用以下示例代码;但是,他们仍然能够读取记录。
任何建议或不同的方法都将受到高度赞赏!
using (Entities context = new Entities(ConnectionString))
{
DBTable entity;
do
{
entity = context.DBTable
.Where(item => item.IsLock == false)
.FirstOrDefault();
if (entity != null)
{
// Map entity to class
......
// Lock the record; it will be unlocked later by a calling method.
entity.IsLock = true;
context.SaveChanges();
count++;
}
} while (entity != null && count < 100);
}
编辑:基本上,我读取记录并做一些事情(有时需要很长时间)。然后使用成功/失败标志更新记录(如果失败,其他人可以再次执行此操作)。我不希望其他应用程序多次成功执行任务。
最佳答案
从评论移至答案:
如果您不介意使用 SQL 修复此问题,请创建一个存储过程。在存储过程中,对记录执行带 UPDLOCK 的 SELECT ( see here for information on table hints )。 SELECT 后,将记录更新为 IsLock。这可以防止在您检查/设置 IsLock 字段时任何其他进程读取数据。
希望有帮助
关于.net - Entity Framework - 记录上的读锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6612652/