简体   繁体   English

EF 6:查询结果不能被多次枚举

[英]EF 6: The result of a query cannot be enumerated more than once

Is there any way to avoid "The result of a query cannot be enumerated more than once" exception without using ToList()? 有没有办法避免不使用ToList()的“查询结果不能被多次枚举”的异常?

Here is a simplified version of my code: 这是我的代码的简化版本:

var entities = _db.Trades.Where(t => t.A > 10);
int totalCount = entities.Count();
entities = entities.Where(t => t.B > 10);
int totalCountAfterAdditionalFilter = entities.Count();

I cannot call ToList() due to performance considerations. 出于性能方面的考虑,我无法调用ToList()。 I know that I could just generate one more IQueryable, but that seems wrong (I have more filters like this). 我知道我可以再生成一个IQueryable,但这似乎是错误的(我有更多这样的过滤器)。 Could I somehow preserve/duplicate the IQueryable after my first call of Count()? 我第一次调用Count()之后,是否可以以某种方式保留/复制IQueryable?

Thanks! 谢谢!

No, you can't achieve your desired result like that. 不,您无法达到预期的效果。 As an alternative you can, however, save your filters to variables and then compose them as needed: 但是,您也可以将过滤器保存到变量中,然后根据需要进行组合:

 Func<Trade, bool> filter1 = t => t.A > 10;
 Func<Trade, bool> filter2 = t => t => t.B > 10;
 Func<Trade, bool> compositeFilter = t => filter1(t) && filter2(t);

 int totalCount = _db.Trades.Count(filter1);
 int totalCountAfterAdditionalFilter  = _db.Trades.Count(compositeFilter);

 //Need more?
 compositeFilter = t => compositeFilter(t) && t.C > 100;
 int totalAfterMoreFilters = _db.Trades.Count(compositeFilter);

may be: 也许:

Trades.Where(x => x.A > 10).Select(x => new { i = 1, j = x.B > 10 ? 1 : 0}).
    GroupBy(y => y.i).
    Select(g => new { c = g.Count(), = g.Sum(z => z.j)})

That's give you the 2 informations in one query. 一次查询即可为您提供2条信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM