Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 911
Scorpion Avatar asked Dec 03 '25 02:12

Scorpion


1 Answers

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.

like image 178
Adriano Repetti Avatar answered Dec 05 '25 15:12

Adriano Repetti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!