簡體   English   中英

帶有條件嵌套的實體框架Linq Include()

[英]Entity framework Linq Include() nested with conditions

我有一個產品,該產品可以通過語言進行一些描述。

我想基於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; }
}

你能做這樣的事情嗎? 您甚至可能不需要.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
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM