Can I use this approach efficiently?
using(SqlCommand cmd = new SqlCommand("GetSomething", new SqlConnection(Config.ConnectionString))
{
cmd.Connection.Open();
// set up parameters and CommandType to StoredProcedure etc. etc.
cmd.ExecuteNonQuery();
}
My concern is : Will the Dispose method of the SqlCommand (which is called when exiting the using block) close the underlying SqlConnection object or not?
Best Answer
No, Disposing of the
SqlCommand
will not effect the Connection. A better approach would be to also wrap theSqlConnection
in a using block as well:Otherwise, the Connection is unchanged by the fact that a Command that was using it was disposed (maybe that is what you want?). But keep in mind, that a Connection should be disposed of as well, and likely more important to dispose of than a command.
EDIT:
I just tested this:
The first command was disposed when the using block was exited. The connection was still open and good for the second command.
So, disposing of the command definitely does not dispose of the connection it was using.