Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it important to Open a sql connection in the transactionscope

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?
  ...
}
like image 465
mkus Avatar asked Dec 29 '09 19:12

mkus


People also ask

What is the use of TransactionScope in C#?

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.

What is transaction scope in SQL Server?

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.

What is an ambient transaction?

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.


2 Answers

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.

like image 76
Oded Avatar answered Sep 29 '22 11:09

Oded


  1. No, command is not executed in transaction
  2. Open connection inside the scope or use EnlistTransaction method of SqlConnection instance. See my answer in different thread.
like image 33
Michal Levý Avatar answered Sep 29 '22 10:09

Michal Levý