Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eager load on polymorphic child object property

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 all parents and eager load all children for each parent and for each Boy load the toy and for each Girl load the book.

How do I write that using Linq Include()?

like image 608
Ian Warburton Avatar asked Aug 09 '13 11:08

Ian Warburton


1 Answers

Can't be done with Include but can be done via projection - EF will wire up navigation properties for you as long as you select those entities (change tracking must be enabled):

var query = db.Parents.Select( p => new
{
    Parent = p,
    // get the children entities for the parent
    Children = p.Children,
    // get the toys for the parent's boys
    Toys = p.Children.OfType<Boy>().Select( b => b.Toy ),
    // get the books for the parent's girls
    Books = p.Children.OfType<Girl>().Select( g => g.Book ),
} );

var results = query.ToArray().Select( at => at.Parent );
like image 175
Moho Avatar answered Nov 11 '22 17:11

Moho