Entity Framework and Eager Load

If you want to Eager Load a relation in entity framework, you can use the Include() method in LINQ to Entities, but the include is useful even With EntitySQl and object services, but the syntax is something that violates the principle of least surprise for me.

I started with:

1
2
3
4
ObjectQuery<Department> query = conn.CreateQuery<Department>(
"Select value d from  Department AS d where d.Name = @name");
query.Parameters.Add(new ObjectParameter("name", "Economics"));
query.Include("Course");

It seems pretty reasonable to me, but this does not work, no eager fetch of any courses….after some minutes of perplexity I realized that the Include Method does return a query object……so the right way to eager fetch the Course collection is

1
query = query.Include("Course");

This sound bad to me, I didn’t really expect that the Include actually creates a complete different query object. It turns out that the best way to do this is chain the Include in the original call.

1
2
3
4
ObjectQuery<Department> query = conn.CreateQuery<Department>(
  "Select value d from Department AS d where d.Name = @name")
 .Include("Course");
query.Parameters.Add(new ObjectParameter("name", "Economics"));

Alk.