2012-03-26 152 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不会混合。基本上投影使用内部选择语句和急切加载的属性使用非规范化和连接来平坦化记录集。