Include Grandchildren in EF Query

Eric J. picture Eric J. · Feb 10, 2013 · Viewed 9.4k times · Source

Given the object hierarchy

public class Parent
{
    public int Id { get; set; }
    public virtual Child Child { get; set; }
}

public class Child
{
    public int Id { get; set; }
    public virtual GrandChild GrandChild { get; set; }
}

public class GrandChild
{
    public int Id { get; set; }
}

and the DB context

public class MyContext : DbContext
{
    public DbSet<Parent> Parents { get; set; }
}

One can include children and grandchildren using Lambda syntax (using System.Data.Entity) like this:

using (MyContext ctx = new MyContext())
{
    var hierarchy = 
        from p in ctx.Parents.Include(p => p.Child.GrandChild) select p;
}

The Lambda syntax prevents breaking the query if the class names are subsequently altered. However, if Parent has an ICollection<Child> like this instead:

public class Parent
{
    public int Id { get; set; }
    public virtual ICollection<Child> Children { get; set; }
}

Lambda syntax no longer works. Instead, one can use the string syntax:

var hierarchy = from p in ctx.Parents.Include("Children.GrandChild") select p;

Is the string syntax the only option, or is there some alternative way to use Lambda syntax in this situation?

Answer

Gert Arnold picture Gert Arnold · Feb 10, 2013

Sure, you can do

var hierarchy = from p in ctx.Parents
                    .Include(p => p.Children.Select(c => c.GrandChild))
                select p;

See MSDN, caption Remarks, the fifth bullet.