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

c# entity-framework-6 linq linq-to-sql

Question

I have four classes Offer, Section, Field, and Option:

Where the offer has sections and every section has some fields and each field has some options as shown:

    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; }
    }

I tried to get the offer by id including the nested entities and this code works perfectly:

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

The problem is when I try to filter the Fields by 'type' like this:

    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);

and I get this error:

The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties. Parameter name: path

I've reviewed lots of questions and still cannot achieve that :(

Linq: query with three nested levels

EF LINQ include nested entities [duplicate]

Using LINQ to query three entitites. - Include path expression must refer to a navigation property defined on the type

1
0
3/22/2020 1:32:25 PM

Popular Answer

Include() is used for Eager loading. It is the process whereby a query for one type of entity also loads related entities as part of the query, so that we don't need to execute a separate query for related entities. Where() is currently not supported inside Include.

1
3/22/2020 2:49:52 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow