views:

39

answers:

1

Does the database connection have to be set inside a TransactionScope?

Or can I set it in the ctor and then have instance methods create up a TransactionScope?

EDIT: e.g.

Public Sub New()
   Dim conn = new SqlConnection(...connection string)
Public Sub SomeClassMethod()
   using ts as new TransactionScope
      //conn has already been initialized
      //so, here you can set commands, ExecuteDataSet, etc.

vs

Public Sub New()
   //nothing here
Public Sub SomeClassMethod()    
   using ts as new TransactionScope
      conn = new SqlConnection(...connection string)
      set commands, ExecuteDataSet, etc.

the question is do you need to create the connection to the database after you've created a TransactionScope or can it be done before?

A: 

If you want you SqlConnection to be under transaction, than you need to create it under TransactionScope.

using(TransactionScope scope = new TransactionScope())
{
  SqlConnection x = new SqlConnestion("....");
  x.Open();
  ....your code... SQlCommands etc....
  x.Close();
  scope.Complete();
}
Fabrizio
Is this equivalent to creating the connection first, then the scope, then inside the scope calling connection.EnlistTransaction( Transaction.Current ). I hope so, because I really need to create a single connection FIRST, then pass it around to various methods that create a transactionscope... and I'd like those methods to enlist the existing connection in the existing transaction scope, so I'm not creating new connections in nested transaction scopes causing them to be escalated to distributed transaction (since multiple connections would be involved).
Triynko