18

I have some code that works like the advised use of TransactionScope, but has an ambient connection instead of an ambient transaction.

Is there a way to use a TransactionScope object with an existing connection, or is there an alternative in the .Net framework for this purpose?

Nathan Ridley
  • 33,766
  • 35
  • 123
  • 197

3 Answers3

34

In fact, there is one way.

connection.EnlistTransaction(Transaction.Current)

It works and it doesnt promote transaction to distributed if not necessary (contrary to what documentation says)

HTH

Michal Levý
  • 33,064
  • 4
  • 68
  • 86
5

To enlist a connection into a TransactionScope, you need to specify 'Enlist=true' in its connection string and open the connection in the scope of that TransactionScope object.

You can use SqlConnection.BeginTransaction on an existing connection.

Update: Can you use BeginTransaction like this:

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

    SqlCommand command = connection.CreateCommand();
    SqlTransaction transaction;

    // Start a local transaction.
    transaction = connection.BeginTransaction("SampleTransaction");

    // Must assign both transaction object and connection
    // to Command object for a pending local transaction
    command.Connection = connection;
    command.Transaction = transaction;

    ...
    ...

}
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • The thing is, the connection is opened in advance of the TransactionScope instantiation; hence the reason for my question. – Nathan Ridley Jun 01 '09 at 11:03
  • @Mitch, Doesn't the connection.BeginTransaction("SampleTransaction") promote to a Distributed Transaction (DTC) in any scenario? If it does, then what are those scenarios? – Baig Jul 28 '11 at 13:24
3

After more research, the answer to my question turned out to be:

No, the connection needs to be opened after the TransactionScope object is instantiated.

Nathan Ridley
  • 33,766
  • 35
  • 123
  • 197