Как TransactionScope управляет транзакцией в SqlConnection? - PullRequest
0 голосов
/ 31 мая 2019

В документации для TransactionScope упоминается, что он неявно управляет транзакциями в своем блоке кода. в следующем примере (снова с того же сайта) он управляет транзакцией через 2 отдельных соединения. Как SQL Connection узнает, что в процессе происходит транзакция? И как TransactionScope управляет транзакцией в SqlConnection?

public int CreateTransactionScope(string connectString1, SqlCredential creds , string commandText1)
{
        // Initialize the return value to zero and create a StringWriter to display results.
        int returnValue = 0;
        System.IO.StringWriter writer = new System.IO.StringWriter();

        try
        {
            // Create the TransactionScope to execute the commands, guaranteeing
            // that both commands can commit or roll back as a single unit of work.
            using (TransactionScope scope = new TransactionScope())
            {
                using (SqlConnection connection1 = new SqlConnection(connectString1,creds))
                {
                    // Opening the connection automatically enlists it in the 
                    // TransactionScope as a lightweight transaction.
                    connection1.Open();

                    // Create the SqlCommand object and execute the first command.
                    SqlCommand command1 = new SqlCommand(commandText1, connection1);
                    returnValue = command1.ExecuteNonQuery();
                    writer.WriteLine("Rows to be affected by command1: {0}", returnValue);

                }

                using (SqlConnection connection2 = new SqlConnection(connectString1, creds))
                {
                    // Opening the connection automatically enlists it in the 
                    // TransactionScope as a lightweight transaction.
                    connection2.Open();

                    // Create the SqlCommand object and execute the first command.
                    SqlCommand command1 = new SqlCommand(commandText1, connection2);
                    returnValue = command1.ExecuteNonQuery();
                    writer.WriteLine("Rows to be affected by command1: {0}", returnValue);

                }

                // The Complete method commits the transaction. If an exception has been thrown,
                // Complete is not  called and the transaction is rolled back.
                scope.Complete();

            }

        }
        catch (TransactionAbortedException ex)
        {
            writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message);
        }

        // Display messages.
        Console.WriteLine(writer.ToString());

        return returnValue;
    }
...