我正在尝试从LINQ查询中检索它:
Question 1 - Answer 1
- Answer 2 (Selected)
- Answer 3
Question 2 - Answer 1
- Answer 2
- Answer 3 (Selected)
etc..
我的表格如下:
Question (with attached multilang support which I'll leave out for now)
QuestionAnswer
Answer (also with multilang)
Response (where the user's response is kept (aka which answer he took -> a specif QuestionAnswer row)
Questionnaire (where all the questionanswers for a single questionnaire are kept)
我已经尝试了以下内容,但是我得到一个异常,说我运行它时无法将.ToList()转换为存储过程(所以在执行时,不是在编译时)(注意这是翻译的) ):
(from culture in DbContext.Culture
from questionanswer in DbContext.QuestionAnswer
join questionnaire in DbContext.Questionnaire on questionanswer .QuestionnaireID equals questionnaire.QuestionnaireID
where culture.TwoLetterISO.Equals(cultureCode) &&
questionnaire.QuestionnaireID == id
select new QuestionnaireSectionInformation()
{
// Additional data is retrieved here, but thats not important for this question
Questions =
((from question in DbContext.Question
join qmultilang in DbContext.QuestionMultiLang on question.ID equals qMultiLang.Id
join response in DbContext.Response on questionanswer.ID equals response.questionanswerId into possibleReponse
where question.ID == questionanswer.QuestionID &&
qMultiLang.CultureId == culture.ID
select new Topic()
{
Question = qMultiLang.Vraag,
Opmerking = possibleResponse.Any() ? possibleResponse.FirstOrDefault().Commentaar : null,
Answers=
((from answer in DbContext.Answer
join aMultiLang in DbContext.AnswerMultiLang on answer.ID equals aMultiLang.Id
where aMultiLang.CultureId == culture.ID
select new Answer()
{
Answer= aMultiLang.Answer,
Selected = possibleAnswer.Any()
}).ToList())
}).ToList())
}).ToList();
我正在尝试学习更多LINQ,这就是为什么我不会把它分开(只需检索数据并从中提取问题和答案)。
所以问题是:我得到一个异常,说当运行它时,.ToList()无法转换为存储过程。如果我不能在它们上面调用.ToList(),我怎样才能得到问题的所有子元素?
答案 0 :(得分:2)
不要在内部查询上调用ToList。请注意,您可以在查询结束时调用ToList,因为该部分不需要转换为T-SQL。
你可能正在使用AsQueryable()而且只在最后一步使用ToList()
这样:
AsQueryable只创建一个查询,获取列表所需的指令。您可以稍后对查询进行进一步更改,例如添加新的Where子句,这些子句一直发送到数据库级别。
AsList返回包含内存中所有项目的实际列表。如果您添加一个新的Where cluse,则不会获得数据库提供的快速过滤。相反,您获取列表中的所有信息,然后过滤掉您在应用程序中不需要的信息,它将作为最终实体呈现,因此不允许进一步修改