How to add where clause to ThenInclude

前端 未结 3 1572
臣服心动
臣服心动 2021-01-11 12:14

I have 3 entities:

Questionnaire.cs:

public class Questionnaire
{
    public int Id { get; set; }
    public string Name { get; set; }
          


        
相关标签:
3条回答
  • 2021-01-11 12:30

    I think you need to have a navigation property of question in your answer because answer should have an question Id . You have this FK already you just need a nav property

    Your model class look like this

    public class Answer
    {
        public int Id { get; set; }
        public string UserId { get; set; }
        public string TextAnswer { get; set; }
        // added in model
        public Question Question { get; set; }
    } 
    

    and query like this

      var answers = ctx.Answers.Include(q=>q.Question).Where(a =>a.UserId=="1").ToList();
    
    0 讨论(0)
  • 2021-01-11 12:34

    Filtering in Include or IncludeThen is not supported. Create projection by using 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);
    

    There is a github issue about this problem: https://github.com/aspnet/EntityFramework/issues/3474

    0 讨论(0)
  • 2021-01-11 12:37

    You can have navigation properties filtered on memory:

    var questionnaire= _context.Questionnaire.FirstOrDefault(qn => qn.Id == questionnaireId);
    
    questionnaire.Answers = _context.Entry(questionnaire)
     .Collection(b => b.Answers )
     .Query()
     .Where(a => a.UserId == userId).ToList();
    
    0 讨论(0)
提交回复
热议问题