c# – 如何向ThenInclude添加where子句

前端之家收集整理的这篇文章主要介绍了c# – 如何向ThenInclude添加where子句前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有3个实体:

Questionnaire.cs:

public class Questionnaire
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Question> Questions { get; set; }
}

Question.cs:

public class Question
{
    public int Id { get; set; }
    public string Text { get; set; }
    public ICollection<Answer> Answers { get; set; }
}

和Answer.cs:

public class Answer
{
    public int Id { get; set; }
    public string UserId { get; set; }
    public string TextAnswer { get; set; }
}

所以我用答案保存了调查问卷,但现在我想找回问题及其答案的过滤问卷.所以我为此写了linq,但它给我一个错误,有什么我做错了吗?这是一个例子:

questionnaire = _context.Questionnaires.Include(qn => qn.Questions)
.ThenInclude(question => question.Answers.Where(a => a.UserId == userId))
.FirstOrDefault(qn => qn.Id == questionnaireId);

而且我得到了

Message = “The property expression ‘q => {from Answer a in q.Answers
where Equals([a].UserId,__userId_0) select [a]}’ is not valid. The
expression should represent a property access: ‘t => t.MyProperty’.

任何想法如何解决这个问题?

解决方法

不支持在Include或IncludeThen中过滤.使用选择创建投影:
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);

关于这个问题有一个github问题:https://github.com/aspnet/EntityFramework/issues/3474

原文链接:https://www.f2er.com/csharp/243309.html

猜你在找的C#相关文章