Search code examples
c#c#-4.0sqldatareaderdbdatareader

DbDataReader error: Invalid attempt to call Read when reader is closed


Hi I am trying to get return the DataReader from a method but it returns a closed DbDataReader object there. Any Idea to sort out this issue. I am open to any suggestions to make the code better.

Thanks

UPDATE I don't want to leave the Database connection Open. is there any way to return the open DataReader after closing the connection.

internal DbDataReader ExecuteReader(SqlCommand command, CommandBehavior behavior, string connectionString)
  {
    DbDataReader dataReader = null;
    try
    {
      SqlConnection connection = GetConnection(connectionString);
      Open(connection);
      command.Connection = connection;
      command.CommandTimeout = 60;
      dataReader = command.ExecuteReader(behavior);
      Close(connection);
    }
    catch
    {
    }
    return dataReader;
}

Solution

  • It's closed because you closed the database connection. It can't read data from a closed SqlConnection. If you want to reuse the connection you may pass an OPEN connection to the method and the close the connection after you consumed data from the DbDataReader.