Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit loading of grandchild collections in EF 4.1

Tags:

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!

like image 326
Slauma Avatar asked May 11 '11 15:05

Slauma


1 Answers

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(); 
like image 109
Ladislav Mrnka Avatar answered Sep 18 '22 07:09

Ladislav Mrnka