使用dapper时关闭阅读器时无效尝试调用Read

时间:2017-03-27 12:07:58

标签: c# asp.net-mvc dapper sqldatareader

使用dapper框架从表中检索记录时,我收到以下错误

  

读取器关闭时调用Read的尝试无效

以下是我的代码

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);
                    }
                }

为什么我收到此错误?

2 个答案:

答案 0 :(得分:4)

您必须打开连接:

using (IDbConnection dbConnection = Connection)
{
   dbConnection.Open() //<--open the connection
   var reader = dbConnection.ExecuteReader(sql);
    ...

答案 1 :(得分:1)

在我非常具体的情况下,我使用了一个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);

希望对某人有帮助