无效的尝试调用Read在使用时读取器已关闭短小精悍
问题描述:
在使用短小精悍的框架,我收到以下错误检索,从表中的记录无效的尝试调用Read在使用时读取器已关闭短小精悍
Invalid attempt to call Read when reader is closed
以下是我的代码
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);
}
}
为什么我收到这个错误?
答
您必须打开连接:
using (IDbConnection dbConnection = Connection)
{
dbConnection.Open() //<--open the connection
var reader = dbConnection.ExecuteReader(sql);
...
答
在我的非常具体的情况下,我使用的是CommandDefinition的选择,它被扔引用的错误:
CommandDefinition queryDefinition = _queryBuilder.UpdateQuery(_dbConn, _transaction, collectionName, item);
await QueryAsync<T>(CommandDefinition);
我改变了它作为遵循和它的工作:
await QueryAsync<T>("SELECT * FROM table_name",param,null,null, commandType : CommandType.Text);
希望它可以帮助给别人