我有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);
我正在接受
消息=&#34;属性表达式&#39; q =&gt; {来自q.Answers中的答案a 其中Equals([a] .UserId,__ userId_0)选择[a]}&#39;无效。该 表达式应代表属性访问:&#39; t =&gt; t.MyProperty&#39;
任何想法如何解决这个问题?
答案 0 :(得分:9)
不支持在Include
或IncludeThen
中过滤。使用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
答案 1 :(得分:0)
我认为您需要在答案中提供问题的导航属性,因为答案应该有问题ID。你已经有了这个FK,你只需要一个导航属性
您的模型类看起来像这样
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; }
}
并像这样查询
var answers = ctx.Answers.Include(q=>q.Question).Where(a =>a.UserId=="1").ToList();
答案 2 :(得分:0)
您可以在内存中过滤导航属性:
<StepTwoTermsOfUse/>