2012-03-26 201 views
0

我想創建一個表格驅動的多項選擇問卷。有一個問題在每個問題中都有孩子的選擇。實體框架延遲加載問題

當我迭代listOfQuestions時,第一個SQL被執行。我認爲通過「包括」選擇,當我循環當前問題的選擇時,這將防止發生次級查找,但事實並非如此。

爲什麼?

var listOfQuestions = (from q in journeyEastContext.Questions.Include("Choices") 
            orderby q.QuestionId 
            select new 
            { 
             Question = q, 
             Choices = q.Choices.OrderBy(c => c.Sequence) 
            }); 


      foreach (var questionGroup in listOfQuestions) 
      { 

       Question question = questionGroup.Question; 

       Literal paragraph = new Literal 
       { 
        Text = "<P/>" 
       }; 
       this.QuestionPanel.Controls.Add(paragraph); 

       Label QuestionLabel = new Label 
       { 
        Text = question.Text 
       }; 
       this.QuestionPanel.Controls.Add(QuestionLabel); 

       //var sortedChoices = from choices in question.Choices 
       //     orderby choices.Sequence 
       //     select choices; 

       foreach (Choice choice in question.Choices) 
       { 
        Literal carrageReturn = new Literal 
        { 
         Text = "<BR/>" 
        }; 
        this.QuestionPanel.Controls.Add(carrageReturn); 

        RadioButton choiceRadioButton = new RadioButton() 
        { 
         ID = String.Format("{0},{1}", question.QuestionId, choice.ChoiceId), 
         Text = choice.Text, 
         GroupName = question.QuestionId.ToString() 
        }; 

        this.QuestionPanel.Controls.Add(choiceRadioButton); 
       } 
      } 

回答

1

這是因爲投影是查詢的一部分。

        select new 
           { 
            Question = q, 
            Choices = q.Choices.OrderBy(c => c.Sequence) 
           }); 

有幾種辦法來處理解決這一點,最簡單的是

var quesitonsList = (from q in journeyEastContext.Questions.Include("Choices") 
           orderby q.QuestionId).ToList(); 



var listOfQuestions = from q in questionsList 
      Select new 
            { 
             Question = q, 
             Choices = q.Choices.OrderBy(c => c.Sequence) 
            }); 

這會告訴EF執行第一查詢(與即時加載的選擇屬性),然後讓你不需要額外的查詢就可以執行迭代。

。因爲在T-SQL中生成的查詢的類型,包含和.Select不會混合。基本上投影使用內部選擇語句和急切加載的屬性使用非規範化和連接來平坦化記錄集。