Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public void UpdateBalance(int accountId, decimal amount)
- {
- using (var connection = new SqlConnection("Your Connection String"))
- {
- connection.Open();
- using (var transaction = connection.BeginTransaction())
- {
- try
- {
- var command = new SqlCommand("SELECT balance, version FROM account_balance WHERE account_id = @accountId", connection, transaction);
- command.Parameters.AddWithValue("@accountId", accountId);
- using (var reader = command.ExecuteReader())
- {
- if (!reader.Read())
- {
- throw new Exception("Account not found");
- }
- var currentBalance = reader.GetDecimal(0);
- var currentVersion = reader.GetInt32(1);
- reader.Close();
- var newBalance = currentBalance + amount;
- var newVersion = currentVersion + 1;
- command = new SqlCommand("UPDATE account_balance SET balance = @balance, version = @version WHERE account_id = @accountId AND version = @currentVersion", connection, transaction);
- command.Parameters.AddWithValue("@balance", newBalance);
- command.Parameters.AddWithValue("@version", newVersion);
- command.Parameters.AddWithValue("@accountId", accountId);
- command.Parameters.AddWithValue("@currentVersion", currentVersion);
- if (command.ExecuteNonQuery() == 0)
- {
- throw new Exception("The balance was updated by another transaction");
- }
- transaction.Commit();
- }
- }
- catch
- {
- transaction.Rollback();
- throw;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment