在EF Core中的何处包含/然后包含

时间:2019-02-10 19:15:18

标签: entity-framework linq api asp.net-core .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();

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

来自This

不支持在 IncludeIncludeThen 中过滤。使用 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);