实体框架嵌套查询Select()问题

编程入门 行业动态 更新时间:2024-10-19 23:47:51
本文介绍了实体框架嵌套查询Select()问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是实体框架的新成员,并尝试使用 Answers 表中的外键获取数据,但出现错误

I am new to the entity framework and trying to get data using foreign key from Answers table but I am getting error

不支持嵌套查询.操作1 =案例"Operation2 =收集"

The nested query is not supported. Operation1='Case' Operation2='Collect'

p.Answers.Count()或 p.Answers.SingleOrDefault().correct_answer 作为字符串可以正常工作,但 p.Answers.Select(c => c.correct_answer).ToList()引发嵌套查询错误

p.Answers.Count() or p.Answers.SingleOrDefault().correct_answeras 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()问题

本文发布于:2023-10-25 13:56:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1527150.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   实体   框架   Select

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!