实体框架 - 读锁定记录 [英] Entity Framework - Read Lock on Record

查看:110
本文介绍了实体框架 - 读锁定记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用实体框架从不同的应用程序调用相同的数据库。但是,当一个应用程序正在读取/更新记录时,我不希望其他应用程序读取该数据。

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.

推荐答案

评论一个答案:

如果您不介意使用SQL修复此问题,请创建一个存储过程。在存储过程中,在记录上执行一个SELECT WITH UPDLOCK(看到这里有关表格的信息提示的)。在SELECT之后,将记录更新为IsLock。这可以防止在检查/设置IsLock字段时任何其他进程读取数据。

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.

希望有助于

这篇关于实体框架 - 读锁定记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆