首页 > 解决方案 > 如何在实体框架 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字段?

我努力了:

标签: c#entity-framework

解决方案


尝试这个:

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。


推荐阅读