3

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

Andre Pena
  • 56,650
  • 48
  • 196
  • 243

2 Answers2

4

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.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • I modified it (EDIT 3) so that the result of idsThatMatch is cached in an array before my next operations. Thank you very much. (you already helped my a lot of times) – Andre Pena Sep 28 '11 at 19:16
1

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?

Community
  • 1
  • 1
Muhammad Hasan Khan
  • 34,648
  • 16
  • 88
  • 131