Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...