Is it ok to dipose a DbCommand before iterating the DbDataReader

807 views Asked by At

I have a simple application that needs to execute certain queries to get the database schema information. I have written a simple method that executes a query and returns a reader, something like this -

public static DbDataReader ExecuteQuery(DbConnection connection,string sql)
{
   DbCommand command = connection.CreateCommand();
   command.CommandText = sql;

   using(command)
   {
      return command.ExecuteReader();    
   }
}

The calling code does close the connection and dispose the reader and connection appropriately.

My question - Is it ok/right to dipose the command instance (as is done via the using block) before iterating the reader? I do not expect any OUT parameters to be populated after closing the reader. Does the ADO.NET API have any strict guidelines regarding this?

1

There are 1 answers

6
Davide Piras On

When you leave the using block in your method command is closed and disposed, if you are able to use the reader from the caller means it still work.

Commands are a mean to execute statements against a connection but do not hold any data this is the reason why this works. As long as the connection is open you can use your reader.

PS. there is also a nice overload of ExecuteReader which instructs the Reader to close the connection directly for you on disposal, useful when connection is created locally like you do with the command and not passed from outside.