c# - 如何在实体框架 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
字段?
我努力了:
.Include(z => z.Animals)
之前_.Join(...)
.Include("Animals")
之前_.Join(...)
.Include(z => z.Zoo.Animals)
之后_.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。
推荐阅读
- javascript - 查看 WebGL 内存
- header - 使用空手道修改标题
- c# - 通过 C# .NET 应用程序调用时无法识别命令,但直接调用时有效
- r - 使用 ShinyFiles::ShinyFileChoose() 访问网络驱动器上的文件时出现问题 - parseFilePaths() 函数返回 NA
- upgrade - Apache Ignite 从 1.8 升级到最新版本
- angular - 如何取消 Ag-grid OnFilterChanged 事件?
- javascript - Swiper.js 延迟图像加载在移动设备上以错误的高度启动
- r - 将每一行连接到 R dplyr 中的整个第二个表
- elasticsearch - Elasticsearch 查询以获取属性出现次数最少的文档列表
- javascript - 有没有办法在javascript中制作一个双输入提示框?(举例)