C# 如何在加入实体框架6后包含集合字段?

C# 如何在加入实体框架6后包含集合字段?,c#,entity-framework,C#,Entity Framework,我有一些基本的EF6型号: 公共阶层人士 { 公共int Id{get;set;} 公共字符串名称{get;set;} } 公立动物园 { 公共int Id{get;set;} public int OwnerId{get;set;} 公共字符串所有者名称{get;set;} 公共i集合动物{get;set;} } 公营动物 { 公共int Id{get;set;} 公共字符串名称{get;set;} public int ZooId{get;set;} [外键(“ZooId”)] 公共动物园{

我有一些基本的EF6型号:

公共阶层人士
{
公共int Id{get;set;}
公共字符串名称{get;set;}
}
公立动物园
{
公共int Id{get;set;}
public int OwnerId{get;set;}
公共字符串所有者名称{get;set;}
公共i集合动物{get;set;}
}
公营动物
{
公共int Id{get;set;}
公共字符串名称{get;set;}
public int ZooId{get;set;}
[外键(“ZooId”)]
公共动物园{get;set;}
}
公共类DbContext:DatabaseContext
{
公共数据库集人物{get;set;}
公共DbSet Zoos{get;set;}
公共数据库集动物{get;set;}
}
当我试图执行这样的查询时,我得到一个空的动物集合

var zoos=\u ctx.Zoo
.Join(_ctx.People,z=>z.OwnerId,p=>p.Id,(z,p=>new{Zoo=z,PeopleName=p.Name})
.ToList();
如何包含
动物
字段

我试过:

  • .Include(z=>z.Animals)
    之前加入(…)
  • .Include(“动物”)
    之前加入(…)
  • .Include(z=>z.Zoo.Animals)
    之后加入(…)
  • .Include(“Zoo.Animals”)
    之后加入(…)
试试这个:

var zoos = _ctx.Zoo
    .Join(_ctx.People, z => z.OwnerId, p => p.Id, (z, p) => new { Zoo = z, PeopleName = p.Name })
    .Select(n=> new {n.Zoo, n.PeopleName, Animals = n.Zoo.Animals})
    .ToList();

这与
Include
不完全相同,但您可以在查询评估后将动物分配给Zoo.Animals。

提示:您不能这样做,因为这将导致非常低效的查询或大量“+1”查询(两者都不好)。取而代之的是,考虑使用<代码> dB。条目(…)。集合(…)。LoadAsync < /代码>。为什么不创建一个FK并使用Include而不是Join呢?就在Join之后,在调用
.ToList()
之前?这是因为在真实的代码模型中
很大,只需要它的
名称
,但每次执行请求时都会加入表。如果你通过EF只得到动物园而没有主人,你就不会加入。那么有什么区别呢?如果你删除了一个人,但你自己的ID将保留在Zoo的?