加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:21:49 所属栏目:百科 来源:网络整理
导读:我有3个实体: Questionnaire.cs: public class Questionnaire{ public int Id { get; set; } public string Name { get; set; } public ICollectionQuestion Questions { get; set; }} Question.cs: public class Question{ public int Id { get; set; }
我有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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读