Transactionscope and uow

Posts   
 
    
methodman
User
Posts: 194
Joined: 24-Aug-2009
# Posted on: 28-Feb-2012 14:07:52   

Hi,

I wrote the following code

         using (var transaction = TransactionUtils.CreateTransactionScope())
         {

                var uow = new UnitOfWork2();            
                uow.Commit(Adapter);

                var uow1 = new UnitOfWork2();       
                uow1.Commit(Adapter);
    
                 Adapter.Commit();
         }

When the code is executed following error will occur

Connection is already part of a local or a distributed transaction

Adapter's lifetime is per request.

I noticed when I use StartTransaction instead of transactionscope the code will work.

        
             Adapter.StartTransaction(IsolationLevel.ReadCommitted, "delete");
            
             var uow = new UnitOfWork2();           
             uow.Commit(Adapter);

             var uow1 = new UnitOfWork2();      
             uow1.Commit(Adapter);
    
             Adapter.Commit();

Could you please explain why is this happening ?

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 28-Feb-2012 18:03:37   

The problem is that you didn't explicity start any transaction on Adapter. uow and uow1 commits are taking care of initiating transactions if needed.

Now, since this is happening in a TransactionScope, you need to complete it:

using (var transaction = TransactionUtils.CreateTransactionScope())
{
      var uow = new UnitOfWork2();          
      uow.Commit(Adapter);

      var uow1 = new UnitOfWork2();     
      uow1.Commit(Adapter);
    
      transaction.Complete();
}

For more info read System.Transactions support.

David Elizondo | LLBLGen Support Team