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;}
}
我想加载所有父母并且急切地为每个父母加载所有孩子,并为每个男孩加载玩具,并为每个女孩加载书。
如何使用Linq Include()编写它?
答案 0 :(得分:4)
无法使用Include
完成,但可以通过投影完成 - 只要您选择这些实体,EF就会为您连接导航属性(必须启用更改跟踪):
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 );