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

时间:2011-01-25 10:33:28

标签: 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;
    }
}

1 个答案:

答案 0 :(得分:5)

你不能(据我所知)

questions = context.Questions.Include("Answers")
                   .OrderBy(answer => answer.Id)
                   .First(question => question.Id == id);

您在此处传递给OrderBy的参数(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);

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

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

var answers = question.Answers.OrderBy(answer => answer.Id);

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

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