Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get a reference to a pending transaction from a SqlConnection object?

Suppose someone (other than me) writes the following code and compiles it into an assembly:

using (SqlConnection conn = new SqlConnection(connString))  {     conn.Open();     using (var transaction = conn.BeginTransaction())     {         /* Update something in the database */         /* Then call any registered OnUpdate handlers */         InvokeOnUpdate(conn);          transaction.Commit();     } } 

The call to InvokeOnUpdate(IDbConnection conn) calls out to an event handler that I can implement and register. Thus, in this handler I will have a reference to the IDbConnection object, but I won't have a reference to the pending transaction. Is there any way in which I can get a hold of the transaction? In my OnUpdate handler I want to execute something similar to the following:

private void MyOnUpdateHandler(IDbConnection conn)  {     var cmd = conn.CreateCommand();     cmd.CommandText = someSQLString;     cmd.CommandType = CommandType.Text;      cmd.ExecuteNonQuery(); } 

However, the call to cmd.ExecuteNonQuery() throws an InvalidOperationException complaining that

"ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized".

Can I in any way enlist my SqlCommand cmd with the pending transaction? Can I retrieve a reference to the pending transaction from the IDbConnection object (I'd be happy to use reflection if necessary)?

like image 509
Rune Avatar asked Jan 06 '09 15:01

Rune


People also ask

How do you use BeginTransaction?

To specify an isolation level with the BeginTransaction method, use the overload that takes the iso parameter (BeginTransaction). The isolation level set for a transaction persists after the transaction is completed and until the connection is closed or disposed.

Does transaction commit close the connection?

By default, in all app server and oracle db, autocommit is true. No matter you use connection pooling or direct connection[DriverManager] since commit is the operation on connection object it doesn't matter.

What is SqlTransaction C#?

The SqlTransaction class is used for satisfying the ACID property of DBMS (I am not describing ACID property here.). It ensure that a body of code will affect a Database or keep the same as previous (Rollback). In this article, I am giving an example of using the SqlTransaction class in . NET using C#.

How does transaction handle in Ado net?

Performing a Transaction Using a Single Connection In ADO.NET, you control transactions with the Connection object. You can initiate a local transaction with the BeginTransaction method. Once you have begun a transaction, you can enlist a command in that transaction with the Transaction property of a Command object.


2 Answers

In case anyone is interested in the reflection code to accomplish this, here it goes:

    private static readonly PropertyInfo ConnectionInfo = typeof(SqlConnection).GetProperty("InnerConnection", BindingFlags.NonPublic | BindingFlags.Instance);     private static SqlTransaction GetTransaction(IDbConnection conn) {         var internalConn = ConnectionInfo.GetValue(conn, null);         var currentTransactionProperty = internalConn.GetType().GetProperty("CurrentTransaction", BindingFlags.NonPublic | BindingFlags.Instance);         var currentTransaction = currentTransactionProperty.GetValue(internalConn, null);         var realTransactionProperty = currentTransaction.GetType().GetProperty("Parent", BindingFlags.NonPublic | BindingFlags.Instance);         var realTransaction = realTransactionProperty.GetValue(currentTransaction, null);         return (SqlTransaction) realTransaction;     } 

Notes:

  • The types are internal and the properties private so you can't use dynamic
  • internal types also prevent you from declaring the intermediate types as I did with the first ConnectionInfo. Gotta use GetType on the objects
like image 84
Alvaro Rodriguez Avatar answered Oct 11 '22 15:10

Alvaro Rodriguez


Wow I didn't believe this at first. I am surprised that CreateCommand() doesn't give the command it's transaction when using local SQL Server transactions, and that the transaction is not exposed on the SqlConnection object. Actually when reflecting on SqlConnection the current transaction is not even stored in that object. In the edit bellow, I gave you some hints to track down the object via some of their internal classes.

I know you can't modify the method but could you use a TransactionScope around the method bar? So if you have:

public static void CallingFooBar() {    using (var ts=new TransactionScope())    {       var foo=new Foo();       foo.Bar();       ts.Complete();    } } 

This will work, I tested using similar code to yours and once I add the wrapper all works fine if you can do this of course. As pointed out watch out if more then one connection is opened up within the TransactionScope you'll be escalated to a Distributed Transaction which unless your system is configured for them you will get an error.

Enlisting with the DTC is also several times slower then a local transaction.

Edit

if you really want to try and use reflection, SqlConnection has a SqlInternalConnection this in turn has a Property of AvailableInternalTransaction which returns an SqlInternalTransaction, this has a property of Parent which returns the SqlTransaction you'd need.

like image 27
JoshBerke Avatar answered Oct 11 '22 16:10

JoshBerke