2012-11-15 29 views
1

我试图从一个LINQ查询检索此: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

*我希望问题清楚* - 我不知道你的问题是什么(也许这只是我)。另外,你发布的数据库模式不是一个模式,它只是一个表名列表。 – Groo

+0

你正在做几个'ToList()'的原因是什么? – Arran

+0

http://stackoverflow.com/questions/12515575/is-there-a-neat-way-of-doing-a-tolist-within-a-linq-query-using-query-syntax – m4ngl3r

回答

2

不要在内部查询上调用ToList。请注意,您可以在查询的末尾调用ToList,因为该部分不需要转换为T-SQL。

你可能会使用AsQueryable已(),而不是只有在使用ToList()最后一步

这样:

AsQueryable已只是创建一个查询,以获取列表所需的指令。您可以稍后对查询进行更改,例如添加新的Where子句,这些子句将一直发送到数据库级别。

AsList返回一个实际列表与内存中的所有项目。如果你添加一个新的Where Cluse,你不会得到数据库提供的快速过滤。相反,您可以获取列表中的所有信息,然后筛选出您在应用程序中不需要的内容,它将作为最终实体呈现,因此不会再进行修改。

+0

谢谢!那么为什么AsEnumerable也可以工作?这不只是返回一个Enumerable? –

+0

http://stackoverflow.com/questions/3628425/ienumerable-vs-list-what-to-use-how-do-they-work做一些googling =) – m4ngl3r

相关问题