使用框架实体,当包括链接表然后Orderby

fre*_*r11 1 entity-framework silverlight-4.0

我在FrameWork Entities中进行了一个查询,该查询使用传入的int id,从1表中返回正确的Question,并使用Include从另一个表中返回相应的Answers.

我想要发生的是所包含的答案是由id排序的.我搜索过但没找到有效的答案.下面的代码是我的原始查询,它与插入的Orderby一起使用.Orderby什么都没做.

如何按照数据库中的顺序获取答案,即Id?

public Question GetQuestionById(int id)
{
    Question questions;

    using (var context = new Entities())
    {
        questions = context.Questions.Include("Answers").OrderBy(answer => answer.Id).First(question => question.Id == id);
        return questions;
    }
}
Run Code Online (Sandbox Code Playgroud)

jer*_*enh 5

你不能(据我所知)

questions = context.Questions.Include("Answers")
                   .OrderBy(answer => answer.Id)
                   .First(question => question.Id == id);
Run Code Online (Sandbox Code Playgroud)

您传递给OrderBy here(answer => answer.Id)的参数具有误导性:您订的是问题,而不是答案.为了澄清,你可以像这样写:

ObjectSet<Question> questions = context.Questions; 
IQueryable<Question> questionsWithAnswers = questions.Include("Answers");
IQueryable<Question> orderedQuestions = questionsWithAnswers
                                           .OrderBy(question => question.Id);
Question question = orderedQuestions.First(question => question.Id == id);
Run Code Online (Sandbox Code Playgroud)

为了做你想做的事情,我相信你只能在从数据库中查询后才能订购:

var question = context.Questions.Include("Answers").First(q => q.Id == id);

var answers = question.Answers.OrderBy(answer => answer.Id);
Run Code Online (Sandbox Code Playgroud)

另一种可能是使用中间匿名类型:

var question = from q in context.Questions
               where q.Id == id
               select new {
                   Question = q, 
                   Answers = q.Answers.OrderBy(answer => answer.Id)
               } 
Run Code Online (Sandbox Code Playgroud)