Dapper Reader Disposed Exception

c# dapper


I did extend the GridReader with the code below;

 /// <summary>
/// </summary>
public static class Extentions
    /// <summary>
    /// Maps the specified reader.
    /// </summary>
    /// <typeparam name="TFirst">The type of the first.</typeparam>
    /// <typeparam name="TSecond">The type of the second.</typeparam>
    /// <typeparam name="TKey">The type of the key.</typeparam>
    /// <param name="reader">The reader.</param>
    /// <param name="firstKey">The first key.</param>
    /// <param name="secondKey">The second key.</param>
    /// <param name="addChildren">The add children.</param>
    /// <returns></returns>
    public static IEnumerable<TFirst> Map<TFirst, TSecond, TKey>
 this Dapper.SqlMapper.GridReader reader,
 Func<TFirst, TKey> firstKey,
 Func<TSecond, TKey> secondKey,
 Action<TFirst, IEnumerable<TSecond>> addChildren
        var first = reader.Read<TFirst>().ToList();
        var childMap = reader
            .GroupBy(s => secondKey(s))
            .ToDictionary(g => g.Key, g => g.AsEnumerable());

        foreach (var item in first)
            IEnumerable<TSecond> children;
            if (childMap.TryGetValue(firstKey(item), out children))
                addChildren(item, children);

        return first;

The reader has been disposed; this can happen after all data has been consumed

the pint here then when the method is called the reader reads all data in the first time but win the method is entered

var first = reader.Read<TFirst>().ToList();

this line give the exception above. so is there any way to keep dapper reader alive to except the query.

thanks in advance .

Note; the method is called like this

  var sql = (@"SELECT *  
                              FROM [pubs].[dbo].[authors] as a
                              right join pubs.dbo.titleauthor as b 
                              ON a.au_id = b.au_idT");

        var data = connection.QueryMultiple(sql).Map<authors, titleauthor, string>(
            au => au.au_id,
            tit => tit.au_idT,
            (au, tits) => { au.titleauthor = tits; });

Accepted Answer

The QueryMultiple API is intended for queries that involve vertical partitions via multiple result grids, i.e. things like:

select * from Parent where Id = @id;
select * from Child where ParentId = @id;

You are using horizontal partitions - you just need to use the Query<,,> API:

var records = connection.Query<TFirst, TSecond, TFirst>(...);

Or: re-structure the SQL to actually return multiple grids.

The reason it is throwing an exception is that your code is requesting a second grid that isn't there.

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