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()?
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With