实体框架 - 记录上的读锁
我使用实体框架从不同应用程序调用相同的数据库。但是,当一个应用程序正在读取/更新记录时,我不希望其他应用程序读取该数据。
我尝试使用以下示例代码;然而,他们仍然能够读取记录。
任何建议或不同的方法将受到高度赞赏!
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);
}
编辑:基本上,我读了一条记录并做了一些事情(有时需要很长时间)。然后使用成功/失败标志更新记录(如果失败,其他人可以再次执行此操作)。我不希望其他应用程序多次成功执行任务。
I'm calling same database from different applications using Entity Framework. However, when one application is reading/updating a record, I do not want other applications to read that data.
I tried with the following sample code; however, they are still able to read the record.
Any suggestion OR different approaches will be highly appreciated!
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);
}
Edited: Basically, I read a record and do something (it sometimes take long). Then update the record with success/fail flag (if fail other can do that again). I do not want other applications do the successful task multiple times.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从评论移至答案:
如果您不介意使用 SQL 修复此问题,请创建一个存储过程。在存储过程中,对记录执行带 UPDLOCK 的 SELECT(有关表的信息请参见此处提示)。 SELECT 后,将记录更新为 IsLock。这可以防止在您检查/设置 IsLock 字段时任何其他进程读取数据。
希望有帮助
Moved from comment to an answer:
If you don't mind fixing this with SQL, create a stored procedure. In the stored procedure do a SELECT on the record WITH UPDLOCK (see here for information on table hints). After the SELECT, update the record to IsLock. This prevents any other process from reading the data whilst you are checking/setting the IsLock field.
Hope that helps