While retrieving the records from table using dapper framework I am getting the below error
Invalid attempt to call Read when reader is closed
and below is my code
var sql = "SELECT * FROM LMS_QuestionCategory";
var rows = new List<Dictionary<string, int>>();
using (IDbConnection dbConnection = Connection)
{
var reader = dbConnection.ExecuteReader(sql);
while (reader.Read())
{
var dict = new Dictionary<string, int>();
for (var i = 0; i < reader.FieldCount; i++)
{
dict[reader.GetName(i)] = reader.GetInt32(i);
}
rows.Add(dict);
}
}
Why I am getting this error ?
You must open the connection:
using (IDbConnection dbConnection = Connection)
{
dbConnection.Open() //<--open the connection
var reader = dbConnection.ExecuteReader(sql);
...
In my very specific case, I was using a CommandDefinition for the select and it was throwing the referenced error:
CommandDefinition queryDefinition = _queryBuilder.UpdateQuery(_dbConn, _transaction, collectionName, item);
await QueryAsync<T>(CommandDefinition);
I changed it as follows and it worked:
await QueryAsync<T>("SELECT * FROM table_name",param,null,null, commandType : CommandType.Text);
Hope it helps to somebody