【问题标题】:Include / ThenInclude with where in EF CoreInclude / ThenInclude 与 EF Core 中的位置
【发布时间】:2019-02-10 19:15:18
【问题描述】:

我需要在 ThenInclude 中使用 where

        var templatesFields = await _context.Sections
        .Include(x => x.Subtitles)
        .ThenInclude(r => r.Fields.Where(t=>t.TemplatesFields.TemplateID==TemplateID))
        .ThenInclude(r => r.OptionSources)
        .ThenInclude(r => r.OptionsSourcesDetails)
        .ToListAsync();

【问题讨论】:

    标签: entity-framework linq api asp.net-core .net-core


    【解决方案1】:

    您不能在 IncludeThenInclude 中使用 where 条件。你可以做的是:

    var templatesFields = await _context.Sections
        .Include(x => x.Subtitles)
        .ThenInclude(r => r.Fields)
        .ThenInclude(r => r.OptionSources)
        .ThenInclude(r => r.OptionsSourcesDetails)
        .Where(t=>t.Subtitles.Fields.Any(x => x.TemplatesFields.TemplateID==TemplateID))
        .ToListAsync();
    

    编辑:.Net Core 5.0(目前处于预览阶段)可以实现这一点

    var blogs = context.Blogs
        .Include(e => e.Posts.Where(p => p.Title.Contains("Cheese")))
        .ToList();
    

    Filtered Include

    【讨论】:

    • 我已经用这种结构制定了我的代码,虽然我还没有因为缺少数据而尝试过,但我还是把它弄好了。谢谢!
    • 我还在学习这个,所以在假设我是对的之前先测试一下,但我很确定这不会按预期工作。 Fields 的 where 子句是为了减少附加到字幕的字段记录,但在提供的解决方案中,它只是删除了任何没有 Subtiutle.Fields 记录的模板。实际上,问题要求“给我所有模板并包括与条件匹配的字段信息”,其中提供的答案是“给我所有模板和模板具有匹配条件的任何字段的所有字段信息。”
    • 这不是问题,它是一个特性。检查 NEt COre 5 learnentityframeworkcore5.com/whats-new-in-ef-core-5/…
    【解决方案2】:

    来自this

    不支持在IncludeThenInclude 中过滤。使用Select创建投影:

    questionnaire = _context.Questionnaires
        .Select(n => new Questionnaire
        {
            Id = n.Id,
            Name = n.Name,
            Questions = n.Questions.Select(q => new Question
            {
               Id = q.Id,
               Text = q.Text,
               Answers = q.Where(a => a.UserId == userId).ToList()
            }).ToList()
        })
        .FirstOrDefault(qn => qn.Id == questionnaireId);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-12
      • 2020-08-24
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-15
      相关资源
      最近更新 更多