2013-02-02 113 views
0

我正在使用ASP.NET MVC4 EF CodeFirst。LINQ到反對EF的實體在多對多關係中

需要幫助在索引操作中編寫LINQ(對實體)代碼以獲取選定學生參加的課程集合。 與有效載荷連接表的關係是多對多關係。

//StudentController 
//----------------------- 

public ActionResult Index(int? id) 
{ 
    var viewModel = new StudentIndexViewModel(); 
    viewModel.Students = db.Students; 

    if (id != null) 
    { 
     ViewBag.StudentId = id.Value; 
     // *************PROBLEM IN LINE DOWN. HOW TO MAKE COURSES COLLECTION? 
     viewModel.Courses = db.Courses 
      .Include(i => i.StudentsToCourses.Where(t => t.ObjStudent.FkStudentId == id.Value)); 
    } 


    return View(viewModel); 
} 

我得到的錯誤是:

The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties. 

我有MODELES(第三個是用於連接表與有效載荷):

//MODEL CLASSES 
//------------- 

public class Student 
{ 
    public int StudentId { get; set; } 
    public string Name { get; set; } 

    public virtual ICollection<StudentToCourse> StudentsToCourses { get; set; } 
} 

public class Course 
{ 
    public int CourseId { get; set; } 
    public string Title { get; set; } 

    public virtual ICollection<StudentToCourse> StudentsToCourses { get; set; } 
} 

public class StudentToCourse 
{ 
    public int StudentToCourseId { get; set; } 
    public int FkStudentId { get; set; } 
    public int FkCourseId { get; set; } 
    public string Classroom { get; set; } 

    public virtual Student ObjStudent { get; set; } 
    public virtual Course ObjCourse { get; set; } 
} 

然後,這裏是模型視圖,我需要通過查看

//VIEWMODEL CLASS 
//--------------- 

public class StudentIndexViewModel 
{ 
    public IEnumerable<Student> Students { get; set; } 
    public IEnumerable<Course> Courses { get; set; } 
    public IEnumerable<StudentToCourse> StudentsToCourses { get; set; } 
} 

回答

1

EF不支持條件包含。你需要包括全部或全部(即沒有0​​裏面的Include

如果你需要獲取某些關係的數據,你可以選擇它到一個匿名類型,像(明顯未經測試);

var intermediary = (from course in db.Courses 
        from stc in course.StudentsToCourses 
        where stc.ObjStudent.FkStudentId == id.Value 
        select new {item, stc}).AsEnumerable(); 

顯然,這需要更改一些代碼,因爲它不再是一個帶有StudentsToCourses集合的直接課程。

+0

謝謝!我正在考慮使用ViewBag來傳遞中間變量來查看。也許「AsNumerable()」應該替換爲「ToList()」?你怎麼看? – Branislav

+0

@Branislav AsEnumerable()'可以替換爲'ToList()',是的。唯一的缺點是如果你繼續對結果進行過濾,那麼在創建一個List()可能不是必須的開銷,並且應該在應用所有過濾器之後完成。 –