【问题标题】:Why do I get a "The result of a query cannot be enumerated more than once" when I get the Count() before enumerating the result?为什么在枚举结果之前获取 Count() 时会出现“查询的结果不能被枚举多次”?
【发布时间】:2011-09-28 18:39:25
【问题描述】:

这是我的代码。为便于阅读而简化

var query = from p in people select p;

// here is the point that probably causes the issue
ObjectResult<int> idsThatMatch = getIdsThatMatchFullTextSearch("andre");
query = from p in query where idsThatMatch.Contains(p.id) select p;

var count = query.Count();
query = query.OrderBy(p => p.id);
var pessoas = query.Skip(90).Take(30).ToList();

我需要在 skip/take 之前读取计数以获取分页前的记录总数。计数工作正常。但在我摘录的最后一行,它触发了异常

一个查询的结果不能多​​次枚举

为什么?顺便说一句,计数不应该枚举任何东西。我该如何解决呢?谢谢

编辑

人们以为我在使用存储过程,但我没有。实际上我正在使用“选择”。代码在评论下方。

编辑 2

我刚刚测试了上面没有“select in”部分的代码,它工作正常

编辑 3

使用这条线有效:

ObjectResult<int> idsThatMatch = (getIdsThatMatchFullTextSearch("andre");
query = from p in query where idsThatMatch.Contains(p.id) select p).ToArray();

谢谢

【问题讨论】:

    标签: .net entity-framework


    【解决方案1】:

    问题出在这一行:

    ObjectResult<int> idsThatMatch = getIdsThatMatchFullTextSearch("andre");
    

    这将返回 ObjectResult 而不是 ObjectQueryIQueryable。结果只能迭代一次。使用Count 执行第一个查询后,您将无法再使用结果,并且您的第二个查询执行将失败,因为它将再次尝试迭代结果。

    ObjectResult 不在数据库端处理 - 它是执行ObjectQuery 的结果,一次执行只能有一个结果集枚举。就像光标在应用程序中遍历结果集一样。

    【讨论】:

    • 我对其进行了修改(编辑 3),以便在我的下一个操作之前将 idsThatMatch 的结果缓存在一个数组中。非常感谢。 (你已经帮了我很多次了)
    【解决方案2】:

    您的人员可能来自实体框架模型中映射的存储过程。 在这种情况下,您不能对其进行过滤或跳过,因为结果已经被评估过。

    The result of a query cannot be enumerated more than once

    The query results cannot be enumerated more than once?

    【讨论】:

    • no no.. 不涉及存储过程。我以前看过这些链接。他们没有多大帮助 =/ 还是谢谢你
    • @AndréPena 人们不能悬在空中。请分享人从哪里来?实际的查询到底是什么样子的。
    • 我会分享它.. 一会儿
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    相关资源
    最近更新 更多