Rollback temporary database changes in C #

I have this problem that seems simple, but searched through the Internet and could not find a solution.

Problem / requirement: In my C # method

  • I want to start a transaction
  • Calling some business logic that ultimately updates the database with complex logic. (written by someone else)
  • Check updated data in the database.
  • rollback changes made in step 2 unconditionally / forcefully. (even if changes are made within the business logic)

I tried to use it System.Transactions.TransactionScope, but it cannot force the undo changes on demand. (changes are not returned when called .Dispose)

+4
source share
2

, . . . .

+1

" -" (.. ), ( ​​).

- - , .

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    // Start a local transaction.
    SqlTransaction sqlTran = connection.BeginTransaction();

    // Enlist a command in the current transaction.
    SqlCommand command = connection.CreateCommand();
    command.Transaction = sqlTran;

    try
    {
        // Here is your "business logic"
        command.CommandText = "INSERT INTO tbBusinessLogic VALUES(1)";
        command.ExecuteNonQuery();

        // Check result
        command.CommandText = "Select 1 from tbBusinessLogic";
        var result = (Int32)command.ExecuteScalar();
        CheckResult(result);

        // Rollback the transaction.
        sqlTran.Rollback();
    }
    catch (Exception ex)
    {
        Logger.LogError(ex);
        sqlTran.Rollback();
    }
}
0

Source: https://habr.com/ru/post/1617189/


All Articles