This is an interesting observation because you cannot use a transaction from another Connection. System.Data.SqlClient.SqlCommand (4.0) has a private member called ValidateCommand that contains several validation checks, including this one:
if ((this._transaction != null) && (this._activeConnection != this._transaction.Connection)) { throw ADP.TransactionConnectionMismatch(); }
The overall design of the SqlCommand class is designed for flexibility. The CommandText, Connection, and Transaction properties (which also appear in three additional constructor overloads) are read / write. This makes the class flexible, but also prone to misuse.
Of course, everything would be much cleaner if the properties were read-only, and the constructors were used as the main means of transferring data to the object. In this case, the following constructor makes sense:
public SqlCommand(string commandText, SqlTransaction transaction)
However, I would suggest that these properties are read / written to enable drag-n-drop constructor support, where the object is built using the default constructor and the properties are set in the InitializeComponent method.
bryanbcook
source share