Entity framework 使用框架实体,当包含链接表时,然后使用Orderby
我在框架实体中进行了一个查询,该查询使用传入的int-id,它从一个表中返回正确的问题,并通过使用Include从另一个表中返回相应的答案 我想做的是,包含的答案是按id排序的。我已经搜索过了,但没有找到一个有效的答案。下面的代码是我使用Orderby插入的原始查询。Orderby一无所获 如何按照答案在数据库中的顺序(Id)获取答案Entity framework 使用框架实体,当包含链接表时,然后使用Orderby,entity-framework,silverlight-4.0,Entity Framework,Silverlight 4.0,我在框架实体中进行了一个查询,该查询使用传入的int-id,它从一个表中返回正确的问题,并通过使用Include从另一个表中返回相应的答案 我想做的是,包含的答案是按id排序的。我已经搜索过了,但没有找到一个有效的答案。下面的代码是我使用Orderby插入的原始查询。Orderby一无所获 如何按照答案在数据库中的顺序(Id)获取答案 public Question GetQuestionById(int id) { Question questions; using (var
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;
}
}
(据我所知)你不能
您在此处传递给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 = from q in context.Questions
where q.Id == id
select new {
Question = q,
Answers = q.Answers.OrderBy(answer => answer.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 = from q in context.Questions
where q.Id == id
select new {
Question = q,
Answers = q.Answers.OrderBy(answer => answer.Id)
}
它会起作用,而您的选项正是在一个数据库往返中获得结果的唯一两种方法。它会起作用,您的选项正是在一个数据库往返中获得结果的唯一两种方法。您应该接受@jeroenh下面的答案,因为答案正确。您应该接受@jeroenh下面的答案,因为答案正确。