实体框架 - 读锁定的记录实体、框架

2023-09-03 15:06:34 作者:←═╬∞男神范~

我打电话从不同的应用程序使用实体框架相同的数据库。但是,当一个应用程序读取/更新记录,我不希望其他应用程序来读取这些数据。

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.

我试着用下面的示例code;然而,他们仍然能够读取记录。

I tried with the following sample code; however, they are still able to read the record.

任何建议或不同的方法将是非常美联社preciated!

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);
}

编辑:基本上,我读了记录,并做一些事情(有时需要很长时间)。然后更新成功记录/失败标志(如果失败,其他的可以再次做到这一点)。我不希望其他应用程序做的成功任务多次。

推荐答案

感动从注释的回答:的

如果你不介意与SQL修复此,创建一个存储过程。在存储过程中做的纪录UPDLOCK一个SELECT(在这里看到的信息,表提示的)。在SELECT后,更新记录IsLock。这prevents读取数据,而你正在检查/设置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.

希望帮助