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

后端 未结 6 512
無奈伤痛
無奈伤痛 2020-12-30 18:51

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

using (SqlConnection conn = new SqlConnection(connString)) 
{
            


        
6条回答
  •  自闭症患者
    2020-12-30 19:34

    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

提交回复
热议问题