开发者

Explicit loading of grandchild collections in EF 4.1

Given the following model ...

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

public class Child
{
    public int Id { get; set; }
    public ICollection<Grandchild> Grandchildren { get; set; }
}

public class Grandchild
{
    public int Id { get; set; }
}

... we can eager load with Include a Parent with all Children and Grandchildren in one step like so:

context.Parents.Include(p => p.Children.Select(c => c.Grandchildren))

Is something similar possible for explicit loading?

The child collection can be explicitely loaded this way:

Parent parent = context.Parents.Find(parentId);
context.Entry(parent).Collection(p => p.Children).Load();

But trying to load the children in a similar way as with Include ...

context.Entry(parent)
    .Collection(p => p.Children.Select(c => c.Grandchildren)).Load();

... doesn't compile und the string overload of Colle开发者_JAVA技巧ction ...

context.Entry(parent).Collection("Children.Grandchildren").Load();

... throws an exception ("...no dotted paths allowed...").

The only thing which I found working is to explicitely load the Grandchildren in a loop:

Parent parent = context.Parents.Find(parentId);
context.Entry(parent).Collection(p => p.Children).Load();
foreach (var child in parent.Children)
    context.Entry(child).Collection(c => c.GrandChildren).Load();

I am wondering if I missed something and if there is some other way to explicitely load the GrandChildren in one roundtrip.

Thanks for feedback in advance!


As I pointed in the comment you can try to get query for relation first, then add includes and execute loading. Something like:

context.Entry(parent)
       .Collection(p => p.Children)
       .Query()
       .Include(c => c.Grandchildren) // I'm not sure if you can include grandchild directly  
       .Load();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜