views:

193

answers:

1

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.

A: 

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

Thomas Levesque
you are right, if use ObjectSet, there is no need to load reference explicitly to call Load(), Include will do the job. But when you can stored procedure and map the result to EntitySet(ResultSet), you need to load reference explicitly. Will try. Weird thing is: the code is working fine at first time when it's done, but later on got above error. Really confused. Thanks.
KentZhou
Have try above code, change IQuerable to IEnumerable, still get the same error message: The result of a query cannot be enumerated more than once.
KentZhou
Fhe error occurs in the foreach loop. How the return value of the method in question has anything to do the line for the foreach?
ydobonmai