Include Grandchildren in EF Query

entity-framework linq-to-entities

Question

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?

1
25
7/3/2017 12:36:23 PM

Accepted Answer

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.

37
2/10/2013 10:30:35 PM

Popular Answer

Update: If you are using Entity Framework Core you should use the following syntax

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


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