Advertisement
Guest User

Untitled

a guest
May 15th, 2024
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.27 KB | None | 0 0
  1.  
  2. var strategy = dbContext.Database.CreateExecutionStrategy();
  3. await strategy.ExecuteAsync(async () =>
  4. {
  5.     using (var transaction = await dbContext.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted))
  6.     {
  7.         var user = await dbContext.Users.NotCacheable().FirstOrDefaultAsync(x => x.UserId == userId);
  8.         if (user == null) return;
  9.         await dbContext.Entry(user).ReloadAsync();
  10.         if (balanceChange < 0 && user.Balance < balanceChange * -1) throw new Exception("UserBalanceNotEnough");
  11.         await dbContext.Database.ExecuteSqlRawAsync(
  12.             "UPDATE Users SET Balance = Balance + {0} WHERE UserId = {1}",
  13.             new object[] { balanceChange, userId });
  14.         var balanceRecord = new BalanceRecord
  15.         {
  16.             UserId = userId,
  17.             Description = description,
  18.             OperatorIp = operatorIp,
  19.             BalanceChange = balanceChange,
  20.             RemainingBalance = user.Balance + balanceChange
  21.         };
  22.         await dbContext.BalanceRecords.AddAsync(balanceRecord);
  23.         try
  24.         {
  25.             await dbContext.SaveChangesAsync();
  26.             await transaction.CommitAsync();
  27.         }
  28.         catch (Exception ex)
  29.         {
  30.             await transaction.RollbackAsync();
  31.         }
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement