简体   繁体   English

使用C#更新Entity Framework中的Balance

[英]UPDATE Balance in Entity Framework using C#

I have a website that has balances & I used to update with a stored procedure: 我有一个拥有余额的网站,并且我以前使用存储过程进行更新:

UPDATE Account 
SET Balance = Balance + @Diff

And it works very well BUT now with C# and Entity Framework, I can only update the value by setting amount (loading value first). 而且它现在在C#和Entity Framework中非常有效,但我只能通过设置数量(首先加载值)来更新值。

I'm ok with loading value before the update BUT I don't like the generated SQL statement: 我可以在更新之前加载值,但是我不喜欢生成的SQL语句:

UPDATE Account 
SET Balance = 6.99

That sucks because if balance gets updated after read and before update (which can be 300ms in EF from load to save) then the balance my be changed in the process. 这很烂,因为如果在读取之后和更新之前更新了余额(从加载到保存,EF可能为300ms),则余额会在此过程中更改。

And to run within a transaction is not really recommended for EF since it causes dead locks. 对于EF,实际上不建议在事务内运行,因为它会导致死锁。

So is there any way to do this correct with EF or do I need to update with the stored procedure? 那么,有什么方法可以使用EF来解决此问题,还是需要使用存储过程进行更新?

Try to use ConcurrencyCheckAttribute : 尝试使用ConcurrencyCheckAttribute

Model: 模型:

public class Account
{
    //other properties...
    [ConcurrencyCheck]
    public decimal Balance {get; set;}
}

Balance update logic: 余额更新逻辑:

while(true)
{
    balance += diff;
    try
    {       
        context.SaveChanges();
        break;
    }
    catch(DbUpdateConcurrencyException)
    {     
        //balance was updated by someone else,
        //so we will get it's last value and try to update again
        context.Entity(balance).Reload();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM