设想:
我有多个帐户。每个帐户都有剩余信用。每个帐户对应多个用户。
我希望 RemainingCredit 字段正确反映剩余信用(我正在使用 EF 抽象出数据库)。
EG在初始信用为X且 2 个用户登录的情况下,一个花费A,一个花费B,我希望最终总和为XAB(读取/修改/保存的顺序应该无关紧要)。
阅读后,我认为乐观并发处理是我正在寻找的,因为它可以很好地扩展,这对我的场景非常重要。最终过程将类似于:
ComputeRemainingCredit(Double amountToBeDeducted) {
Account acc = context.Accounts.Where(condition)
ComputeRemainingCreditInternal(acc, amountToBeDeducted);
}
ComputeRemainingCreditInternal(Account acc, Double amountToBeDeducted) {
try {
acc.RemainingCredit = acc.RemainingCredit - amountToBeDeducted;
context.SaveChanges();
}
catch (OptimisticConcurrencyException ex) {
context.Refresh(RefreshMode.StoreWinds, acc);
//now I need to rerun the operation
ComputeRemainingCreditInternal(acc, amountToBeDeducted);
}
}
- 这是 EF 中乐观并发的正确解释/实现吗?
- 我的最终目标是更新 RemainingCredit 字段。有没有比 OptimisticConcurrencyException 更好的解决方案?