簡體   English   中英

使用 LINQ 查詢四個嵌套實體。 - 包括 Where 條件

[英]Using LINQ to query four nested entities. - Include Where condition

我有四個類 Offer、Section、Field 和 Option:

報價有部分,每個部分都有一些字段,每個字段都有一些選項,如下所示:

    public class Offer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public ICollection<Section> Sections { get; set; }
    }

    public class Section
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public ICollection<Field> Fields { get; set; }
    }

    public class Field
    {
        public int Id { get; set; }
        public string Type { get; set; } //[question, group]
        public ICollection<Option> Options { get; set; } 
    }

    public class Option
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

我試圖通過 id 獲取報價,包括嵌套實體,這段代碼完美運行:

    var offer = _context.Offers
        .Include(o => o.Sections
            .Select(s => s.Fields
            .Select(f => f.Options)))
        .FirstOrDefault(o => o.Id == offerId);

問題是當我嘗試按“類型”過濾字段時,如下所示:

    var offer = _context.Offers
        .Include(o => o.Sections
            .Select(s => s.Fields.Where(f => f.Type == "question")
            .Select(f => f.Options)))
        .FirstOrDefault(o => o.Id == offerId);

我收到這個錯誤:

Include 路徑表達式必須引用類型上定義的導航屬性。 對參考導航屬性使用虛線路徑,對集合導航屬性使用 Select 運算符。 參數名稱:路徑

我已經審查了很多問題,但仍然無法做到這一點:(

Linq:具有三個嵌套級別的查詢

EF LINQ 包括嵌套實體 [重復]

使用 LINQ 查詢三個實體。 - 包含路徑表達式必須引用類型上定義的導航屬性

Include() 用於 Eager 加載。 在這個過程中,對一種類型的實體的查詢也會加載相關實體作為查詢的一部分,這樣我們就不需要對相關實體執行單獨的查詢。 Include 中目前不支持 Where()。

如果您只想過濾結果,您可以執行以下操作:

        var offer = _context.Offers
         .Include(o => o.Sections
         .Select(s => s.Fields
         .Select(f => f.Options)))
         .FirstOrDefault(o => o.Id == offerId);
        var filtered_offer = 
        new Offer
        {
            Sections = offer.Sections.Select(S => new Section
            {
                Id = S.Id,
                Name = S.Name,
                Fields = S.Fields.Where(f => f.Type == "question").ToList()
            }).ToList(),
            Id = offer.Id,
            Name = offer.Name
        };

暫無
暫無

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

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