实体框架Linq Include()与条件嵌套

时间:2017-08-17 13:44:00

标签: c# .net entity-framework linq

我有一个产品,这个产品可以用语言进行一些描述。

我希望根据product.ReferenceLanguage.Code获取符合语言代码的产品和说明。我使用EF Core 2.0

我可以通过2个单独的查询来完成,但如果可能的话我会喜欢。

我试过了:

var product = _context.Products
    .Where(x => x.Reference == "3265709")
    .Include(x => x.ProductDescriptions)
    .ThenInclude(x => x.Where(lg => lg.Language.Code == "EN").Select(z => z.Language))
    .ToList();

有什么想法吗?

谢谢,

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Reference { get; set; }
    public ICollection<ProductDescription> ProductDescriptions{ get; set; }
}

public class ProductDescription
{
    public int Id { get; set; }
    public string Short { get; set; }
    public string Complete { get; set; }
    public Language Language{ get; set; }
    public Product Product { get; set; }
}

public class Language
{
    public int Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

1 个答案:

答案 0 :(得分:1)

你可以这样做吗?您甚至可能不需要.Any()部分。

var product = _context.Products.Where(x => x.Reference == "3265709" && x.ProductDescriptions.Any(a => a.Language.Code == "EN"))
   .SelectMany(x => x.ProductDescriptions.Where(z => z.Language.Code == "EN").Select(a => a.Language)).ToList();

编辑:

这是你正在寻找的吗?这应该为您提供一个产品列表,其中包含指定的参考代码和基于语言代码的过滤产品描述列表。

var product = _context.Products.Where(x => x.Reference == "3265709" && x.ProductDescriptions.Any(a => a.Language.Code == "EN")).Select(x => new Product {
      Id = x.Id,
      Name = x.Name,
      ProductDescriptions = x.ProductDescriptions.Where(a => a.Language.Code == "EN").ToList(),
      Reference = x.Reference
});