Using Framework Entities, when Include a linked table then Orderby
I have a query made in FrameWork Entities that uses a int id which is passed in, which brings back the correct Question from 1 table and also brings back the corresponding Answers from another table by using an Include.
What I want to happen is that the included answers are ordered by the id's. I have searched but not found an answer that works. The code below is my original query that works with a Orderby inserted. The Orderby achieves nothing.
How do I get the Answers in the order they are in the database, the Id's?
public Question GetQue开发者_如何学JAVAstionById(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;
}
}
You can't (to my knowledge)
questions = context.Questions.Include("Answers")
.OrderBy(answer => answer.Id)
.First(question => question.Id == id);
The parameter you pass to OrderBy here (answer => answer.Id
) is misleading: you're ordering the questions, not the answers. To clarify, you could write it like this:
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);
In order to do what you want, I believe you can only order after you query them from the database:
var question = context.Questions.Include("Answers").First(q => q.Id == id);
var answers = question.Answers.OrderBy(answer => answer.Id);
Another possibility might be to use an intermediate anonymous type:
var question = from q in context.Questions
where q.Id == id
select new {
Question = q,
Answers = q.Answers.OrderBy(answer => answer.Id)
}
精彩评论