Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include Grandchildren in EF Query

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?

like image 884
Eric J. Avatar asked Feb 10 '13 18:02

Eric J.


1 Answers

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.

like image 158
Gert Arnold Avatar answered Oct 25 '22 23:10

Gert Arnold