精简程序给出“当阅读器关闭时无效的调用FieldCount的尝试".尝试使用"QueryMultiple"时 [英] Dapper giving "Invalid attempt to call FieldCount when reader is closed." when trying to use "QueryMultiple"

查看:255
本文介绍了精简程序给出“当阅读器关闭时无效的调用FieldCount的尝试".尝试使用"QueryMultiple"时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Dapper.NET的QueryMultiple方法的包装方法.它成功地从存储过程中获取数据,该存储过程具有3个查询,所有查询均为SELECT查询.但是获取数据后,我不能使用ReadReadAsync将数据分配给类变量.我在下面附上我的代码.

I have a wrapper method for Dapper.NET's QueryMultiple method. It successfully gets data from a Stored Procedure, which has 3 queries, all of them are SELECT queries. But after getting the data, I cannot use Read or ReadAsync to assign data to class variables. I'm attaching my code below.

public Tuple<IEnumerable<T1>, IEnumerable<T2>, IEnumerable<T3>> 
        QueryMultiple<T1, T2, T3>()
    {
        try
        {
            var data = MultiQuery("[App].[USP_GetAllCategories]");
            var category = data.Read<T1>();
            var subcategory = data.Read<T2>();
            var subSubcategory = data.Read<T3>();
            return new Tuple<IEnumerable<T1>, IEnumerable<T2>, IEnumerable<T3>>(
                category, subcategory, subSubcategory);
        }
        catch (Exception)
        {
            return null;
        }
    }

    public SqlMapper.GridReader MultiQuery(string storedProcedureName)
    {
        using (var connection = LocalConnection())
        {
            try
            {
                return connection.QueryMultiple(
                    sql: storedProcedureName,
                    commandType: CommandType.StoredProcedure);
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                CloseConnection(connection);
            }
        }
    }

推荐答案

查看您的MultiQuery方法.特别是,请查看finally块.现在考虑:在使用数据之前已调用该块.基本上,不要那样做.

Look at your MultiQuery method. In particular, look at the finally block. Now consider: that block has been called before the data has been consumed. Basically, don't do that.

如果是我:

using (var connection = LocalConnection())
uaing (var data = conn.QueryMultiple("[App].[USP_GetAllCategories]",
    command type: CommandType.StoredProcedure))
{
    //... Consume
}

如果编写添加命令类型的QueryMultipleSP扩展方法很有帮助,则可以这样做,但是...

If it is helpful to write a QueryMultipleSP extension method that adds the command-type, then maybe do that, but...

这篇关于精简程序给出“当阅读器关闭时无效的调用FieldCount的尝试".尝试使用"QueryMultiple"时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆