1

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

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

2 回答 2

0

这里的技巧是使用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;
于 2020-11-14T14:24:31.580 回答
0

另一种方法是使用 Join 运算符。例如>

from currentBrand in Context.Brand 加入 currentModel 在 context.Model on currentBrand.Id 等于 currentModel.BrandId 加入 currentGeneration 在 context.Generations on currentGeneration.ModelId 等于 currentModel.id 加入 currentModeification 在 context.Modification on currentModeification.GenerationId 等于 currentGeneration .Id 其中 currentModeification .ModificationName == "确认"

于 2020-11-14T15:51:53.223 回答