SharePoint Newbie
SharePoint Newbie

Reputation: 6082

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?

Upvotes: 3

Views: 655

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109205

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.

Upvotes: 1

Related Questions