I have a classic balance update concurrency situation:
using (var context = GenerateContext())
{
var account = context.Accounts.First(x => x.id == accountId);
var balanceBefore = account.balance;
// ... do some other stuff ...
account.balance = balanceBefore + depositAmount;
context.SubmitChanges();
}
I would like to lock the whole table for reads/writes during this update.
Can it be done with Linq2SQL?
Edit:
So I tried the following, which does lock the table during the transaction, but it doesn't preform the update - the balance never changes.
using (var context = GenerateContext())
{
context.Connection.Open();
context.Transaction = context.Connection.BeginTransaction(IsolationLevel.Serializable);
var account = context.ExecuteQuery<Account>("SELECT TOP 1 * FROM [Account] WHERE [Id] = 10 WITH (TABLOCKX)").First();
var balanceBefore = account.balance;
// ... do some other stuff ...
account.balance = balanceBefore + depositAmount;
context.SubmitChanges();
}
What am I doing wrong?