在使用 dapper 时关闭 reader 时调用 Read 的尝试无效

Invalid attempt to call Read when reader is closed while using dapper

使用 dapper 框架从 table 检索记录时出现以下错误

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

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

希望对大家有所帮助