问题描述
我是实体框架的新成员,并尝试使用 Answers
表中的外键获取数据,但出现错误
I am new to the entity framework and trying to get data using foreign key from Answers
table but I am getting error
p.Answers.Count()
或 p.Answers.SingleOrDefault().correct_answer
作为字符串可以正常工作,但 p.Answers.Select(c => c.correct_answer).ToList()
引发嵌套查询错误
p.Answers.Count()
or p.Answers.SingleOrDefault().correct_answer
as string works fine but p.Answers.Select(c => c.correct_answer).ToList()
throwing nested query error
我想将其保留在一个查询中,因为可能有成千上万的问题,所以我不想检查单独查询的答案.以下是我的代码.
I want to keep it in one query because there could be thousands of questions so I don't want to check answers to the separate queries. Following is my code.
return db.Questions.Where(p => p.q_id == q_id).Select(p => new QuestionViewModel
{
q_id = p.q_id,
q_text = p.q_text,
q_answer = p.Answers.Count() > 0 ? p.Answers.Select(c => c.correct_answer).ToList() : null
}).OrderBy(x => x.q_id).ToList();
ViewModel
public class QuestionViewModel
{
public long q_id { get; set; }
public string q_text { get; set; }
public List<string> q_answer { get; set; }
}
推荐答案
例外是告诉您EF不支持条件子查询,该表达式由以下表达式暗示:
The exception is telling you that EF does not support conditional subquery, implied by expressions like this:
p.Answers.Count() > 0 ? p.Answers.Select(c => c.correct_answer).ToList() : null
因此只需删除条件运算符:
So simply remove the conditional operator:
q_answer = p.Answers.Select(c => c.correct_answer).ToList()
如果没有相关问题的答案, q_answer
将填充 empty 列表,而不是 null
,这是正常的(预期)集合类型对象的行为.
In case there are no related answers for question, q_answer
will be populated with empty list rather than null
, which is the normal (expected) behavior for collection type objects.
这篇关于实体框架嵌套查询Select()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!