10
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() 编写它?

4

1 回答 1

5

无法完成,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 );
于 2017-10-03T13:46:30.387 回答