Include grandchildren in EF Query

Given the hierarchy of objects

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 DB context

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

You can enable children and grandchildren using the lambda syntax ( using System.Data.Entity ) as follows:

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

Lambda syntax prevents query violation if class names are subsequently changed. However, if Parent has ICollection<Child> instead:

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

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

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

Is string syntax the only option or is there an alternative way to use lambda syntax in this situation?

+16
linq-to-entities entity-framework
Feb 10 '13 at 18:57
source share
2 answers

Of course you can do

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

See MSDN , Note Header, Fifth Mark.

+28
Feb 10 '13 at 22:30
source share

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; 
+11
Aug 03 '16 at 11:10
source share



All Articles