2016-07-08 64 views
0

我用下面的代碼段有問題:如何在實體框架中實現雙重包含?

public class Course 
{ 
    [Key] 
    public Guid CourseId { get; set; } 
    public Subject CourseSubject { get; set; } 
    public List<Student> CourseAttendeeStudents { get; set; } 
    public Teacher CourseTeacher { get; set; } 

    public Course() 
    { 
     CourseNotes = new List<CourseNote>(); 
     CourseAttendeeStudents = new List<Student>(); 
     CourseSubject = new Subject(); 
     CourseId = Guid.NewGuid(); 
    } 
} 

我需要收集有關所有課程的所有信息,所以我做了以下內容:

var coursed = db.Courses.Include(p=>p.CourseAttendeeStudents).Include(p=>p.CourseTeacher); 

然而,學生和教師包含另一個在自己內部列出。 我怎麼可以這樣做:

var coursed = db.Courses.Include(p=>p.CourseAttendeeStudents.Include...).Include(p=>p.CourseTeacher.Include...); 

回答

1

Check out this article about entity loading

有一段名爲急切地加載多個層次。

的例子,他們給:

// Load all blogs, all related posts, and all related comments 
var blogs1 = context.Blogs 
        .Include(b => b.Posts.Select(p => p.Comments)) 
        .ToList(); 

也許是這樣的:

var coursed = db.Courses 
       .Include(p => p.CourseAttendeeStudents.Select(s => s.OtherListInsideAttendeeStudent)) 
       .Include(p => p.CourseAttendeeStudents.StudentProperty.Select(s =>s.OtherListInsideStudentProperty)) 
       .Include(p => p.CourseTeacher.Select(s => s.OtherListInsideTeacher)); 
0

我不知道你正在運行的實體框架的版本,但至少在覈心,有一個「 ThenInclude「函數可以使用。

var coursed = db.Courses 
    .Include(p=>p.CourseAttendeeStudents) 
     .ThenInclude(courseAttendeeStudents => courseAttendeeStudents.Property) 
    .Include(p=>p.CourseTeacher) 
     .ThenInclude(courseTeacher => courseTeacher.Property); 

如上所示,它建立在你已經做過的Include()上。您可以繼續添加ThenInclude。