【问题标题】:When does Dapper 'materialize'? Like Entity materializes at ToList()Dapper 什么时候“实现”? Like Entity 在 ToList() 实现
【发布时间】:2017-01-31 10:18:31
【问题描述】:

标题几乎说明了一切。由于 Dapper 没有太多文档。提前致谢。

【问题讨论】:

    标签: entity-framework orm dapper


    【解决方案1】:

    Query() 返回 IEnumerable。当您开始迭代您的 IEnumerable 时,在 Dapper 内部会使用 Yield 调用一些方法来用一行结果填充 POCO,因此当您迭代它们时,您的结果会逐步实现。您需要在执行此操作时保持数据库连接打开,因为您不能保证结果集的所有行都立即返回。实际上,对于大型结果集,您希望能够在不将整个结果集保存在应用程序内存中的情况下遍历它们。在任何时候,您都可以在您的 IEnumerable 上调用 ToList(),然后您已经实现了所有内容,您可以关闭您的连接。

    【讨论】:

    • 谢谢@user1585345。因此,Dapper 在ToList() 实现,并且在我们迭代结果时。
    • 不完全。您可能永远不会调用 ToList() 在这种情况下,您的结果会逐行具体化(迭代)。如果您确实调用 ToList() all 您的结果将被实现。
    【解决方案2】:

    如您所见,结果在查询执行后立即具体化。

    Dapper - 版本 1.50.5

    public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
    {
            CommandDefinition command = new CommandDefinition(sql, param, transaction, commandTimeout, commandType, buffered ? CommandFlags.Buffered : CommandFlags.None);
            IEnumerable<T> enumerable = cnn.QueryImpl<T>(command, typeof(T));
            if (!command.Buffered)
            {
                return enumerable;
            }
            return enumerable.ToList();
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-25
      • 2013-09-09
      • 1970-01-01
      • 1970-01-01
      • 2017-11-11
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多