c# - Dapper Reader 处置异常

标签 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;
    }
}

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

然后这里的品脱当方法被调用时reader在第一时间读取所有数据但是win进入方法

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

这一行给出了上面的异常(exception)情况。那么除了查询之外,有什么方法可以让 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; });

最佳答案

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

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

您正在使用水平分区 - 您只需要使用 Query<,,>应用程序接口(interface):

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

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

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

关于c# - Dapper Reader 处置异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19271298/

相关文章:

c# - 备用应用程序。在 Program.cs 文件中运行 Winform

c# - 无法在 C# 中使用 Gmail SMTP 发送邮件

c# - 如何使用 Dapper Dot Net 从数据库结果映射到 Dictionary 对象?

c# - 如何让 Dapper.Rainbow 在 SQLite 中使用 AutoIncrement 插入到表中?

c# - 如何读取 Dapper 生成的 SQL 查询?

c# - 您应该如何处理存储库模式中的父实体和子实体?

javascript - 图像->JSON->.Net 图像

f# - 适用于 F# 联合类型的简洁通用类型处理程序

c# - 捕获 NullReference Exception 时获取哪个字段为 null?

c# - 如何在 MVC 中使用 Dapper 插入数据并返回插入的标识?