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?
This my code. Simplified for readability
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();
I need to read the count before skip/take to get the total amount of records before paging. The count works fine. But at the last line of my excerpt it triggers the exception
The result of a query cannot be enumerated more than once
Why? The count isn't supposed to enumerate anything by the way. And how can I solve that? Thank you
EDIT
People thought I was using stored procedures but I'm not. Actually I'm using a "select in". The code is bellow the comment.
EDIT 2
I just tested the above code without the "select in" part and it works fine
EDIT 3
开发者_开发问答Using this line works:
ObjectResult<int> idsThatMatch = (getIdsThatMatchFullTextSearch("andre");
query = from p in query where idsThatMatch.Contains(p.id) select p).ToArray();
Thank you
The problem is this line:
ObjectResult<int> idsThatMatch = getIdsThatMatchFullTextSearch("andre");
This returns ObjectResult
not ObjectQuery
or IQueryable
. Result can be iterated only once. Once you execute your first query with Count
you cannot use result anymore and your second query execution will fail because it will try to iterate result again.
ObjectResult
is not processed on database side - it is the result of executed ObjectQuery
and one execution can have only one enumeration of result set. It is like cursor to iterate through result set in your application.
Your people may be coming from a stored procedure mapped in Entity Framework model. In that case you can not do filtering or skipping on it since the result has already been evaluated.
The result of a query cannot be enumerated more than once
The query results cannot be enumerated more than once?
精彩评论