Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var strategy = dbContext.Database.CreateExecutionStrategy();
- await strategy.ExecuteAsync(async () =>
- {
- using (var transaction = await dbContext.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted))
- {
- var user = await dbContext.Users.NotCacheable().FirstOrDefaultAsync(x => x.UserId == userId);
- if (user == null) return;
- await dbContext.Entry(user).ReloadAsync();
- if (balanceChange < 0 && user.Balance < balanceChange * -1) throw new Exception("UserBalanceNotEnough");
- await dbContext.Database.ExecuteSqlRawAsync(
- "UPDATE Users SET Balance = Balance + {0} WHERE UserId = {1}",
- new object[] { balanceChange, userId });
- var balanceRecord = new BalanceRecord
- {
- UserId = userId,
- Description = description,
- OperatorIp = operatorIp,
- BalanceChange = balanceChange,
- RemainingBalance = user.Balance + balanceChange
- };
- await dbContext.BalanceRecords.AddAsync(balanceRecord);
- try
- {
- await dbContext.SaveChangesAsync();
- await transaction.CommitAsync();
- }
- catch (Exception ex)
- {
- await transaction.RollbackAsync();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement