Error: A query's result can't be enumerated more than once.

domainservices entity-framework

Question

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.

1
1
7/20/2010 8:15:31 PM

Popular Answer

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

4
7/20/2010 9:54:29 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow