Error: The result of a query cannot be enumerated more than once

KentZhou picture KentZhou · Jul 20, 2010 · Viewed 9.9k times · Source

Call SP in EF 4.0 in following code:

  public IQueryable<Employee> GetEmployeesByFollowup()
        {
            var results = from p in this.ObjectContext.SearchEmployeeFollowup()
                          select p;
            foreach (Employee p in results)
            {
                p.DepaermentReference.Load();                
            }
            return results.AsQueryable<Employee>();
        }

Following error caused in For loop:

"The result of a query cannot be enumerated more than once."} System.SystemException {System.InvalidOperationException}

It seems it's working fine for sometime. Don't undertstand why.

Answer

Thomas Levesque picture Thomas Levesque · Jul 20, 2010

Returning a IQueryable from a method is only useful if you want to add something to the query (filter, projection, join...) before it is executed. But since your method enumerates the results with foreach, the query has already been executed when you return it, so it is too late to add anything to it...

Perhaps your method should return a IEnumerable<Employee> instead:

    public IEnumerable<Employee> GetEmployeesByFollowup()
    {
        var results = this.ObjectContext.SearchEmployeeFollowup().ToList();
        foreach (Employee p in results)
        {
            p.DepaermentReference.Load();
        }
        return results;
    }

BTW, EF 4.0 handles lazy loading of related entities, so you normally don't have to call Load explicitly