Dapper giving "Invalid attempt to call FieldCount when reader is closed." when trying to use "QueryMultiple"

asp.net-web-api2 c# dapper

Question

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

Accepted Answer

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.

If it was me:

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

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



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why