For some reason, SqlCommand.Transaction
is not getting set. The code that sets it is definitely getting called (verified in debugger), but after the property is set, the property is still null
.
Here's the code...
cmd.Connection = cmd.Connection ?? Connection;
cmd.Transaction = cmd.Transaction ?? Transaction;
if (cmd.Transaction == null && Transaction != null)
{
var t = Transaction;
cmd.Transaction = t;
}
Definition of Transaction...
private SqlTransaction Transaction { get; set; }
I added the if statement in case the problem was the coalesce operator (??), but it doesn't seem to help (didn't expect it to, but grasping at straws now).
I looked at the C# code for SqlCommand.Transaction
and there is a path where the field won't get set, but in that scenario, an exception is thrown, not to mention that the condition shouldn't be met anyway (SqlCommand.cs source code).
Any suggestions would be appreciated.
I did determine that SqlTransaction.Connection is null.
That is the problem. You may be setting the cmd.Transaction
property OK, but when you read it back out, the SqlCommand
will check the cmd.Transaction.Connection
property, and if it is null, it sets cmd.Transaction
back to null. This might make it seem like you never set it to begin with. Note that it does not raise an exception in this scenario. Here is the relevant source code.
new public SqlTransaction Transaction
{
get
{
if ((null != _transaction) && (null == _transaction.Connection))
{
_transaction = null;
}
return _transaction;
}
/* snip */
}