2013-08-17 33 views
5

Tôi có các lớp sau:Làm thế nào tôi có thể. Bao gồm nhiều hơn một cấp trong LINQ?

public class Problem : AuditableTable 
{ 
    public Problem() 
    { 
     this.Questions = new List<Question>(); 
    } 
    public int ProblemId { get; set; } 
    public string Title { get; set; } 
    public virtual ICollection<Question> Questions { get; set; } 
} 

public Question() 
    { 
     this.Answers = new List<Answer>(); 
    } 
    public int QuestionId { get; set; } 
    public int ProblemId { get; set; } 
    public virtual ICollection<Answer> Answers { get; set; } 
    public virtual Problem Problem { get; set; } 
} 
public class Answer : AuditableTable 
{ 
    public int AnswerId { get; set; } 
    public int QuestionId { get; set; } 
    public string Text { get; set; } 
    public virtual Question Question { get; set; } 
} 

tôi muốn phát hành một truy vấn như thế này:

 var problems = _problemsRepository.GetAll() 
      .Where(p => p.ProblemId == problemId) 
      .Include(p => p.Questions) 
      .Include(p => p.Questions.Answers) 
      .ToList(); 
     return problems; 

Vì vậy, tôi có thể thấy vấn đề, câu hỏi và câu trả lời thông tin. Nhưng có một vấn đề với tôi bao gồm cuối cùng và tôi không thể làm việc ra làm thế nào để có được câu trả lời bao gồm.

Ai đó có thể cho tôi một số lời khuyên về điều này.

Trả lời

5

Bạn có thể sử dụng .Select().

var problems = _problemsRepository.GetAll() 
      .Where(p => p.ProblemId == problemId) 
      .Include(p => p.Questions.Select(q => q.Answers)) 
      .ToList(); 

Bây giờ, câu trả lời của bạn sẽ được bao gồm.

+1

Đầu tiên 'Include' là lỗi thời. Câu hỏi thứ hai cũng sẽ bao gồm các câu hỏi. – user2674389

+0

@ user2674389 Đã cập nhật! Cảm ơn đã bình luận rằng .. –

4

Điều này đã thay đổi trong EntityFramework 7.0.

Cú pháp mới sẽ mang hình thức

var problems = _problemsRepository.GetAll() 
      .Where(p => p.ProblemId == problemId) 
      .Include(p => p.Questions) 
      .ThenInclude(q => q.Answers) 
      .ToList(); 
+0

Ah finnaly là một giải pháp cho EF 7. Đã tìm kiếm điều này cho các lứa tuổi chỉ thấy rằng EF 7 đã không hỗ trợ tải lười biếng được nêu ra và các giải pháp trước đây không làm việc -_- – stibay

Các vấn đề liên quan