I created a sqlconnection, CN1. Then this CN1 is opened. Later in the code there is a transactionscope. If I execute a sql command on this CN1 connection, is this within transaction?
Code looks like this;
SqlConnection cn1 = new SqlConnection();
cn1.Open(); //connection opened when there is no ambient transaction.
...
using(TransactionScope scope = new TransactionScope())
{
SqlCommand cmd; //a typical sql command.
...
cmd.ExecuteNonQuery(); //Is this command within transaction?
...
}
The TransactionScope class provides a simple way to mark a block of code as participating in a transaction, without requiring you to interact with the transaction itself. A transaction scope can select and manage the ambient transaction automatically.
The TransactionScope class makes a code block transactional by implicitly enlisting connections in a distributed transaction. You must call the Complete method at the end of the TransactionScope block before leaving it. Leaving the block invokes the Dispose method.
An ambient transaction is one that works at the thread level. Thus, all operations that occur in that context will be part of the transaction.
It is a MUST to open the connection within the TransactionScope to ensure that the connection is enrolled in the transaction.
This is found in the comment just above the connection.Open
in this MSDN example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With