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

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


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


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.


For anybody who is interested in the C# version of the decorator class that Denis made in VB.NET, here it is:

using System;using System.Collections.Generic;using System.Text;using System.Data;namespace DataAccessLayer{    /// <summary>    /// Decorator for the connection class, exposing additional info like it's transaction.    /// </summary>    public class ConnectionWithExtraInfo : IDbConnection    {        private IDbConnection connection = null;        private IDbTransaction transaction = null;        public IDbConnection Connection        {            get { return connection; }        }        public IDbTransaction Transaction        {            get { return transaction; }        }        public ConnectionWithExtraInfo(IDbConnection connection)        {            this.connection = connection;        }        #region IDbConnection Members        public IDbTransaction BeginTransaction(IsolationLevel il)        {            transaction = connection.BeginTransaction(il);            return transaction;        }        public IDbTransaction BeginTransaction()        {            transaction = connection.BeginTransaction();            return transaction;        }        public void ChangeDatabase(string databaseName)        {            connection.ChangeDatabase(databaseName);        }        public void Close()        {            connection.Close();        }        public string ConnectionString        {            get             {                return connection.ConnectionString;             }            set             {                connection.ConnectionString = value;            }        }        public int ConnectionTimeout        {            get { return connection.ConnectionTimeout; }        }        public IDbCommand CreateCommand()        {            return connection.CreateCommand();        }        public string Database        {            get { return connection.Database; }        }        public void Open()        {            connection.Open();        }        public ConnectionState State        {            get { return connection.State; }        }        #endregion        #region IDisposable Members        public void Dispose()        {            connection.Dispose();        }        #endregion    }}