DbTransaction and DbConnection when working with EF4

1k views Asked by At

I'm trying to implement a Unif Of Work around ObjectContext of EF4 in a web application. The UoW is an HttpModule. What I need is to get the current transaction for the connection. When an http request first commes I start the transaction on the objectContext with context.Connection.BeginTransaction(). On the request end I need to retrieve the current transaction for the connection but there is no property to do that on the Connection object. I made the following code to achieve it but it doesn't work.

private DbTransaction GetTransaction()
             {
                      if (_currentTransaction == null)
                      {
                               var command = GetSession().Connection.CreateCommand(); // just to get the current transaction
                               if (command.Transaction != null)
                                        _currentTransaction = command.Transaction;
                               else
                                        _currentTransaction = GetSession().Connection.BeginTransaction();
                      }

                      return _currentTransaction;
             }

I don't understand why the command.Transaction is always null. If I try to do GetSession().Connection.BeginTransaction() I get the exception that the transation already exists and can't start several transactions in parrallel.

GetSession() retrives just the current EF ObjectContext from HttpContext.Current.Items. ObjectContext is stored there on beginRequest.

If you give me some guidance I will appreciate.

Thanks.

1

There are 1 answers

1
Craig Stuntz On

ObjectContext.Connection isn't your store connection; it's an EntityConnection.

You probably want TransactionScope. If you want to start a transaction on the store only, then you want ((EntityConnection)Context.Connection).StoreConnection.