【问题标题】:Using LINQ to query four nested entities. - Include Where condition使用 LINQ 查询四个嵌套实体。 - 包括 Where 条件
【发布时间】:2020-03-22 13:32:25
【问题描述】:

我有四个类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);

我得到这个错误:

包含路径表达式必须引用在类型上定义的导航属性。对引用导航属性使用虚线路径,对集合导航属性使用 Select 运算符。 参数名称:路径

我已经审查了很多问题,但仍然无法做到这一点:(

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

【问题讨论】:

  • _context.Offers .Include(o => o.Sections).ThenInclue(s=>s.Fields) .Select(s => s.Fields.Where(f => f.Type = =“问题”)
  • 我认为 ThenInclude 方法只在 EF Core 中,而不是在 .NET Framework 中
  • 没错,您的预期结果是什么?
  • 我要过滤filed.type = "questions":not get all fields的字段
  • 如何使用 .Net 框架实现您在第一条评论中所写的内容

标签: c# linq linq-to-sql entity-framework-6


【解决方案1】:

Include() 用于急切加载。这是对一种类型的实体的查询也将相关实体作为查询的一部分加载的过程,因此我们不需要对相关实体执行单独的查询。目前在 Include 中不支持 Where()。

【讨论】:

    【解决方案2】:

    如果你只想过滤结果,你可以这样做:

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

    【讨论】:

    • 我收到此错误兄弟:无法在 LINQ to Entities 查询中构造实体或复杂类型“Tadawlat.RequestsDb.Offer”。
    猜你喜欢
    • 2013-03-23
    • 1970-01-01
    • 2011-11-02
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 2020-07-19
    • 1970-01-01
    相关资源
    最近更新 更多