如何在实体框架中完全锁定一行 [英] How to totally lock a row in Entity Framework

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

问题描述

我正在处理我们处理货币交易的情况.

I am working with a situation where we are dealing with money transactions.

例如,我有一张用户钱包表,其余额在该行中.

For example, I have a table of users wallets, with their balance in that row.

UserId; Wallet Id; Balance

现在,在我们的网站和网络服务中,每当发生某笔交易时,我们都需要:

Now in our website and web services, every time a certain transaction happens, we need to:

  1. 检查是否有足够的资金来执行该交易:
  2. 从余额中扣除交易费用.

在整个交易过程中如何锁定行/实体的正确方法是什么?

How and what is the correct way to go about locking that row / entity for the entire duration of my transaction?

从我所阅读的内容中,可以找到一些解决方案,其中EF标记了一个实体,然后在将其保存回数据库时比较了该标记,但是当另一个用户/程序已经编辑了该数量时,该怎么办?

From what I have read there are some solutions where EF marks an entity and then compares that mark when it saves it back to the DB, however what does it do when another user / program has already edited the amount?

我可以使用EF实现吗?如果没有,我还有什么其他选择?

Can I achieve this with EF? If not what other options do I have?

调用存储过程是否可以使我正确地锁定该行,以便在程序A对其进行锁定的同时,没有其他人可以访问SQL Server中的该行?

Would calling a stored procedure possibly allow for me to lock the row properly so that no one else can access that row in the SQL Server whilst program A has the lock on it?

推荐答案

EF没有内置的锁定机制,您可能需要使用原始查询,如

EF doesn't have built-in locking mechanism, you probably would need to use raw query like

using (var scope = new TransactionScope(...))
{
    using (var context = new YourContext(...))
    {
        var wallet = 
            context.ExecuteStoreQuery<UserWallet>("SELECT UserId, WalletId, Balance FROM UserWallets WITH (UPDLOCK) WHERE ...");

        // your logic

        scope.Complete();
    }
}

这篇关于如何在实体框架中完全锁定一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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