[英]How to include collection field after Join in Entity Framework 6?
我有一些基本的 EF6 模型:
public class People
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Zoo
{
public int Id { get; set; }
public int OwnerId { get; set; }
public string OwnerName { get; set; }
public ICollection<Animal> Animals { get; set; }
}
public class Animal
{
public int Id { get; set; }
public string Name { get; set; }
public int ZooId { get; set; }
[ForeignKey("ZooId")]
public Zoo Zoo { get; set; }
}
public class DbContext : DatabaseContext
{
public DbSet<People> People { get; set; }
public DbSet<Zoo> Zoos { get; set; }
public DbSet<Animal> Animals { get; set; }
}
当我尝试执行这样的查询时,我得到一个空的 Animals 集合
var zoos = _ctx.Zoo
.Join(_ctx.People, z => z.OwnerId, p => p.Id, (z, p) => new { Zoo = z, PeopleName = p.Name })
.ToList();
如何包含Animals
字段?
我试过了:
.Join(...)
之前的.Include(z => z.Animals)
.Join(...)
.Include("Animals")
之前的.Join(...)
.Join(...)
之后的.Include(z => z.Zoo.Animals)
.Join(...)
.Join(...)
之后的.Include("Zoo.Animals")
.Join(...)
尝试这个:
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
不完全一样,但您可以在查询评估后将 Animals 分配给 Zoo.Animals。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.