实体框架 - 悲观锁定 [英] Entity Framework - pessimistic locking

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

问题描述

我想要做的是基本上是 NHibernate做什么,当你做这样的事情:

What I am trying to do is basically what NHibernate does when you do something like:

var instance = session.Get<Customer>(id, LockMode.Upgrade);

我需要锁定数据库中的实体行。为什么我需要这个
想象一下像工作流实例,可以由多个演员(人或进程)同时更新。

I need to lock the entity row in the database. Why I need that? Imagine something like a workflow instance that can be updated by multiple actors(people or processes) at the same time.

我的约束不允许乐观的锁定解决方案。

The constraints I have don't allow for optimistic locking solutions.

推荐答案

EF不支持这一点。如果要通过查询锁定一些记录,则必须执行以下操作:

EF doesn't have support for this. If you want to lock some record by query you must do something like:

using (var scope = new TransactionScope(...))
{
    using (var context = new YourContext(...))
    {
        var customer = 
            context.ExecuteStoreQuery<Customer>("SELECT ... FROM Customers WITH (UPDLOCK) WHERE ...");

        // rest of your logic while record is locked

        scope.Complete();
    }
}

context.Database。 SqlQuery 在DbContext API的情况下。

Or context.Database.SqlQuery in case of DbContext API.

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

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