Explicit loading of grandchild collections in EF 4.1

拟墨画扇 提交于 2019-12-20 11:22:32

问题


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 Collection ...

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!


回答1:


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();


来源:https://stackoverflow.com/questions/5966994/explicit-loading-of-grandchild-collections-in-ef-4-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!