.Net: Does my connection close through Dispose in this example?

Here is 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 a command is selected, is the connection closed? Or do I need this first using statement to be for the connection, and then create the command in close?

+5
source share
3 answers

If you want the reader to close the connection, you can use the ExecuteReader () overload:

...
using (IDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)) 
...

By default, deleting the reader does not release the connection. - see MSDN for more information ...

To resolve the Close()vs issue Dispose(), MSDN states:

If the DbConnection goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling Close or Dispose, which are functionally equivalent.

, . , , . , Dispose(), null, , .

+11

, . :

using (SqlConnection conn = (SqlConnection)DataAccessHelper.CreateDatabase().CreateConnection())
using (DbCommand cmd = new SqlCommand("myProcedure", conn) { CommandType = CommandType.StoredProcedure })
{
    cmd.Connection.Open();
    using(IDataReader dr = cmd.ExecuteReader())
        doWork(dr);
}
+4

using(var connection = (SqlConnection)DataAccessHelper.CreateDatabase().CreateConnection())
{
 connection.Open(); 
 ....
}

Because even if you close the connection, you still need to dispose of it. Note what SQLConnectioncauses Closein Dispose. The problem is that if you were to call on your Closeown, you would need to put it in try...catchso that it is guaranteed, and you would not have a memory leak. There are other types in the structure that are not called Closein Dispose, which, in my opinion, should be wrapped.

+3
source

All Articles