Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
            }
        }
    }
like image 302
haider_kazal Avatar asked Jan 04 '16 05:01

haider_kazal


1 Answers

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

like image 70
Marc Gravell Avatar answered Oct 21 '22 14:10

Marc Gravell