我正在尝试创建一个由表驱动的多项选择问卷。有一个问题在每个问题中都有子选择。
当我迭代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);
}
}
答案 0 :(得分: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执行第一个查询(急切加载Choices属性),然后让你在没有激发额外查询的情况下运行迭代。
.Include和.Select不要混用,因为在T-SQL中生成的查询类型。基本上,投影使用内部选择语句,并且急切加载的属性使用非规范化和连接来展平记录集。