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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…