首页 > 解决方案 > 英孚为孙辈选择祖父母

问题描述

类品牌、车型、世代、改装

如何获取 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; }
}

标签: entity-frameworklinq

解决方案


这里的技巧是使用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;

推荐阅读