0

I wrote method in my database layer to be consumed by other upper layers. This method returns IDataReader as shown below:

public IDataReader GetDataReader(string commandText, CommandType commandType, IDbDataParameter[] parameters)
{
     IDataReader reader = null;

     using (var connection = _database.GetConnection())   //either opens new or uses existing connection if exist
     {
           using (var command = _database.GetCommand(commandText, connection, commandType))
           {
               {
                   if (parameters != null)
                   {
                        foreach (var parameter in parameters)
                        {
                            command.Parameters.Add(parameter);
                        }
                   }
                   reader = command.ExecuteReader();
                   return reader;
                }
           }
     }
}

Now when i want to consume that method somewhere else and when it reaches while (reader.Read()) it gave me an error.

private void GetResult()
{
    var query = "SELECT * FROM MyTable";
    var reader = Context.GetDataReader(query, CommandType.Text, null);

    while (reader.Read())
    {
         //...
    }
}

Error:

'Invalid attempt to call Read when reader is closed.'

What could i do to fix that?

Arie
  • 3,041
  • 7
  • 32
  • 63

0 Answers0