Here’s a simplified version of my example:
using (DbCommand cmd = new SqlCommand("myProcedure", (SqlConnection)DataAccessHelper.CreateDatabase().CreateConnection()) { CommandType = CommandType.StoredProcedure })
{
cmd.Connection.Open();
using(IDataReader dr = cmd.ExecuteReader())
doWork(dr);
}
When the command is disposed, is the connection closed? Or would I need to have that first using statement be for the connection, and then create the command in the closure?
If you want the reader to close the connection, you can use the overload of ExecuteReader():
By default, disposing a reader does not release the connection. – see MSDN for more info…
To address the question of
Close()vsDispose(), the MSDN states:Thus a self-closing connection need not be disposed necessarily. The main difference is that a closed connection can be re-opened, but a disposed connection cannot. The main additional work that
Dispose()does is set internals tonullwhich won’t have much of an effect since the connection is passing out of scope anyway.