2011-01-25 42 views
1

我有一個在FrameWork實體中的查詢,它使用一個int id傳入,這將從1表中帶回正確的問題,並從另一個表中帶回相應的答案表使用Include。使用框架實體時,包括一個鏈接的表然後orderby

我想要發生的是,包含的答案是由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

您應該接受@ jeroenh的答案,因爲答案正確。 – Slauma 2011-11-15 18:33:34

回答

5

你不能(據我所知)

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

傳遞給排序依據這裏(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) 
       } 
+0

它將起作用,你的選擇正是在一次數據庫往返中獲得結果的兩種方法。 – Slauma 2011-11-15 18:30:19