Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
999 views
in Technique[技术] by (71.8m points)

entity framework - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...