I am new to EF and SQL in general, so I could use some help clarifying this point.
Let's say I have a wallet table (and a code key of the first EF code code) with an identifier and balance. I need to do this operation:
if(wallet.balance > 100){ doOtherChecksThatTake10Seconds(); wallet.balance -= 50; context.SaveChanges(); }
As you can see, it checks if the condition is really valid, then if so, you need to perform a bunch of other operations that take a lot of time (in this exaggerated example we say 10 seconds), then if it is he subtracts $ 50 from the wallet and saves new data.
The problem is that there are other things that can change the wallet balance at any time (this is a web application). If this happens:
- wallet.balance = 110;
- this operation passes the if check because wallet.balance> 110
- when he executes the doOtherChecksThatTake10Seconds () command, the user transfers $ 40 from his wallet
- now wallet.balance = 70
- "doOtherChecksThatTake10Seconds ()" completes, subtracts 50 from the wallet. Balance and then save the context with the new data.
In this case, the wallet check> balances> 100 is no longer valid, but the operation is still due to a delay. I need to find a way to lock the table and not let it go until the whole operation is completed, so nothing is edited during the editing process. What is the most efficient way to do this?
It should be noted that I tried to perform this operation in TransactionScope (), I'm not sure if this will have the intended effect or not, but I noticed that it started to cause a lot of deadlocks with a completely different database operation that works.
source share