Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do multiple level eager loading in Entity Framework 4.3 when I have a polymorphic collection?

I have the following classes:

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

public class Child
{      
}

public class Boy : Child
{  
  public Toy Toy {get;set;}    
}

public class Girl : Child
{      
  public Book Book {get;set;}
}

I want to load a parent with all boys eagerly:

Parents.Include(p => p.Children.OfType<Boys>().Select(b => b.Toy));

The above does not work and I get the error saying that the path is invalid.

How do I accomplish this?

like image 823
SharePoint Newbie Avatar asked Dec 03 '25 16:12

SharePoint Newbie


1 Answers

I think in this case the extension method Include resolves to a string "Boys" which, obviously, can not be included by the member method Include.

Even if this would run, I suspect it would be a problem to have a Children collections that is only filled with Boy objects. For me that would be an indeterminate state of the collection, because it represents the children of the parent. So it either should contain all children or yet be empty.

If you often need the Boys collection (or the real life pendant of it) and its references (Toy) you should map it as a separate navigation property. Otherwise do the OfType() on the Children collection.

like image 101
Gert Arnold Avatar answered Dec 06 '25 15:12

Gert Arnold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!