Slavik9510

Untitled

Nov 26th, 2023
704
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.93 KB | None | 0 0
  1. public void UpdateBalance(int accountId, decimal amount)
  2. {
  3.     using (var connection = new SqlConnection("Your Connection String"))
  4.     {
  5.         connection.Open();
  6.  
  7.         using (var transaction = connection.BeginTransaction())
  8.         {
  9.             try
  10.             {
  11.                 var command = new SqlCommand("SELECT balance, version FROM account_balance WHERE account_id = @accountId", connection, transaction);
  12.                 command.Parameters.AddWithValue("@accountId", accountId);
  13.  
  14.                 using (var reader = command.ExecuteReader())
  15.                 {
  16.                     if (!reader.Read())
  17.                     {
  18.                         throw new Exception("Account not found");
  19.                     }
  20.  
  21.                     var currentBalance = reader.GetDecimal(0);
  22.                     var currentVersion = reader.GetInt32(1);
  23.  
  24.                     reader.Close();
  25.  
  26.                     var newBalance = currentBalance + amount;
  27.                     var newVersion = currentVersion + 1;
  28.  
  29.                     command = new SqlCommand("UPDATE account_balance SET balance = @balance, version = @version WHERE account_id = @accountId AND version = @currentVersion", connection, transaction);
  30.                     command.Parameters.AddWithValue("@balance", newBalance);
  31.                     command.Parameters.AddWithValue("@version", newVersion);
  32.                     command.Parameters.AddWithValue("@accountId", accountId);
  33.                     command.Parameters.AddWithValue("@currentVersion", currentVersion);
  34.  
  35.                     if (command.ExecuteNonQuery() == 0)
  36.                     {
  37.                         throw new Exception("The balance was updated by another transaction");
  38.                     }
  39.  
  40.                     transaction.Commit();
  41.                 }
  42.             }
  43.             catch
  44.             {
  45.                 transaction.Rollback();
  46.                 throw;
  47.             }
  48.         }
  49.     }
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment