linq Include / ThenInclude with where in EF Core [duplicate]

watbbzwu  于 2023-11-14  发布在  其他
关注(0)|答案(2)|浏览(164)

此问题在此处已有答案

Filtering on Include in EF Core(9个回答)
19小时前关闭
我需要使用Where in ThenInclude

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

字符串

a8jjtwal

a8jjtwal1#

Pirior to .Net 5:

你不能在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 5:

从.Net Core 5.0开始,这是可能的

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


Filtered Include

cyej8jka

cyej8jka2#

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

字符串

相关问题