Dapper Reader处理异常

时间:2013-10-09 11:53:58

标签: c# dapper

我确实使用下面的代码扩展了GridReader;

 /// <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
            .Read<TSecond>()
            .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;
    }
}
  

读者被处置;这可能发生在所有数据消耗后

这里的品脱然后当调用该方法时,读者在第一次读取所有数据但是输入了方法

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

这一行给出了上述例外。那么除了查询之外,还有什么办法让dapper reader保持活着。

提前感谢。

请注意;该方法就像这样调用

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

1 个答案:

答案 0 :(得分:9)

QueryMultiple API适用于通过多个结果网格涉及垂直分区的查询,例如:

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

您正在使用水平分区 - 您只需使用Query<,,> API:

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

或者:重新构造SQL以实际返回多个网格。

它抛出异常的原因是您的代码正在请求不存在的第二个网格

相关问题