0

I wrote a linq query to fetch multiple nested entities. I need to get all the questions except the ones that are deleted and the ones with a parentId. This is where it's going wrong. All the results are fine, except the result set still contains questions where the parent id is not null. What am I doing wrong?

I think it might has to do with the filterquestions, these are also questions self referring to another question. I need these questions only in the list of filterquestions and not in both.

public async Task<QuestionList?> GetAsyncQuestionTree(Guid id)
{
    var tree = await _dbContext.QuestionLists
        .Where(list => list.Id == id)
        .Include(list => list.Modules)!
            .ThenInclude(module => module.Questions!.Where(m => m.isDeleted == false && m.ParentId == null))!
                .ThenInclude(question => question.AnswerOptions)
        .Include(list => list.Modules)!
            .ThenInclude(module => module.Questions!.Where(m => m.isDeleted == false && m.ParentId == null))!
            .ThenInclude(question => question.FilterQuestions)
                .ThenInclude(question => question.AnswerOptions)
        .FirstOrDefaultAsync();

    return tree;
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Heis
  • 606
  • 5
  • 25
  • [`Include` does not filter the query, only included collections](https://stackoverflow.com/a/61147681/861716). – Gert Arnold Aug 15 '23 at 07:23
  • @GertArnold Thanks, although if I just do a single include it does work. I'll check the link you send to find out how I could make this work – Heis Aug 15 '23 at 08:39
  • BTW what I said is the Incudes don't filter `_dbContext.QuestionLists`, but that wasn't relevant, actually. But if questions are interrelated somehow, yes then other questions may enter the result, but that's hard to judge w/o seeing the classes. – Gert Arnold Aug 15 '23 at 08:56

0 Answers0