entity-framework - 英孚为孙辈选择祖父母
问题描述
类品牌、车型、世代、改装
如何获取 ModificationName == "ACK" 的所有品牌
public class Brand
{
public Brand()
{
this.Models = new HashSet<Model>();
}
public int BrandId { get; set; }
public virtual ICollection<Model> Models { get; set; }
}
public class Model
{
public Model()
{
this.Generations = new HashSet<Generation>();
}
public virtual ICollection<Generation> Generations { get; set; }
public int? BrandId { get; set; }
public virtual Brand Brand { get; set; }
}
public class Generation
{
public Generation()
{
this.Modifications = new HashSet<Modification>();
}
public int GenerationId { get; set; }
public virtual ICollection<Modification> Modifications { get; set; }
public int? ModelId { get; set; }
public virtual Model Model { get; set; }
}
public class Modification
{
public int ModificationId { get; set; }
public string ModificationName { get; set; }
public int? GenerationId { get; set; }
public virtual Generation Generation { get; set; }
}
解决方案
这里的技巧是使用SelectMany
方法。
var query =
from b in ctx.Brands
where b.Models
.SelectMany(m => m.Generations.SelectMany(g => g.Modifications))
.Where(m => m.ModificationName == "ACK").Any()
select b;
更新包含
它仅适用于 EF Core 5
var query =
from b in ctx.Brands
.Include(b => b.Models)
.ThenInclude(g => g.Generations)
.ThenInclude(m => m.Modifications.Where(x => x.ModificationName == "ACK"))
where b.Models
.SelectMany(m => m.Generations.SelectMany(g => g.Modifications))
.Where(m => m.ModificationName == "ACK").Any()
select b;
推荐阅读
- java - 如何配置 Hibernate 以使用标准日志记录
- asp.net-core - 从 Cache Tag Helper 中逐出缓存
- apache-camel - 无法让骆驼故障转移连接到代理
- drupal - 如何在 Drupal 8 中为 CKEditor 字体模块添加额外的 cambria 字体
- java - 如何使用 guice 在我的控制器中注入我的服务类?
- python - 我只需要在 pyspark 数据框中附加那些具有非空值的人
- spring - 使用 oauth2-client 作为隐式授权类型时解决 [authorization_request_not_found]
- java - 谷歌地图不能在所有设备上运行,而在其他设备上运行。我该怎么办?
- indexing - CouchDB 中 $elemMatch 的索引
- javascript - Javascript 代码在本地工作,但在现场不工作