Include / ThenInclude 与 EF Core 中的 where

Ray*_*yan 3 linq api entity-framework .net-core asp.net-core

我需要在 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();
Run Code Online (Sandbox Code Playgroud)

Der*_*ğlu 12

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

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();
Run Code Online (Sandbox Code Playgroud)

编辑:这可以通过 .Net Core 5.0(现在处于预览状态)

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

过滤包含

  • 我仍在学习这一点,因此在假设我是对的之前先对其进行测试,但我很确定这不会按预期工作。Fields 的 where 子句是为了减少附加到字幕的字段记录,但在提供的解决方案中,它只是删除任何没有 Subtiutle.Fields 记录的模板。实际上,问题要求“给我所有模板并包括与条件匹配的字段信息”,而提供的答案则为“给我所有模板以及模板具有与条件匹配的任何字段的所有字段信息”。 (2认同)