如何在WhereInclude中添加where子句 [英] How to add where clause to ThenInclude

查看:76
本文介绍了如何在WhereInclude中添加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,但它抛出了一个错误,我做错了什么吗?这是示例:

So I saved the questionnaire with answers but now i want to retrieve filtered questionnaire with questions and its answers. So i wrote linq for that, but it throws me an error, is there anything i do wrong? here is the example:

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

我正在

消息=属性表达式'q => {来自q.Answers中的答案a 其中Equals([a] .UserId,__userId_0)选择[a]}'无效.这 表达式应表示对属性的访问:"t => t.MyProperty".

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'.

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

Any ideas how to solve this problem?

推荐答案

不支持在IncludeIncludeThen中进行过滤.使用Select创建投影:

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

有关此问题的github问题: https://github.com/aspnet/EntityFramework /issues/3474

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

这篇关于如何在WhereInclude中添加where子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆