2012-11-15 30 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

相關問題