2012-03-21 202 views
3

有人可以指出我哪裏有錯!代碼第一個實體框架多對多的關係

我創建了2個簡單的類,具有多對多的關係。工作正常,所有的表都填寫正確。除了當我嘗試retrive返回課程沒有任何學生...

public partial class Student 
{ 

    public Student() 
    { 
     Courses = new HashSet<Course>(); 
    } 

    public int StudentID { get; set; } 

    [StringLength(50)] 
    [Required] 
    public string FirstName { get; set;} 

    [StringLength(50)] 
    [Required] 
    public string LastName {get; set;} 

    public DateTime? Enroled {get;set;} 

    public ICollection<Course> Courses { get; set; } 


} 

public class Course 
{ 

    public Course() 
    { 
     Students = new HashSet<Student>(); 
    } 
    public int CourseID { get; set; } 

    [StringLength(30)] 
    [Required] 
    public string CourseTitle { get; set; } 

    [StringLength(255)] 
    public string CourseDesc { get; set; } 

    public ICollection<Student> Students { get; set; } 
} 

    public ContextDB() 
     : base (@"Data Source=.\SQLEXPRESS;Initial Catalog=CollegeDB;Integrated Security=True") 
    { 

    } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Course>().HasMany(c=>c.Students).WithMany(p => p.Courses) 
      .Map(
      m=> { 
       m.MapLeftKey("Course_CourseID"); 
       m.MapRightKey("Student_StudentID"); 
       m.ToTable("CourseStudents"); 
      }); 
    } 

    public DbSet<Student> Students { get; set; } 
    public DbSet<Course> Courses { get; set; } 


} 



      var students = db.Students.ToList(); 

      foreach (Student s in students) 
      { 
       Console.WriteLine("{0} {1}", s.FirstName, s.LastName); 
       foreach (Course c in s.Courses.ToList()) 
       { 
        Console.WriteLine("{0}", c.CourseTitle); 
       } 
      } 

回答

8

如果使用延遲加載,你需要defiine性質爲虛,

public virtual ICollection<Course> Courses { get; set; } 

,如果你願意,你可以使用預先加載,

var students = db.Students.Include(s=>s.Courses).ToList(); 

http://codetuner.blogspot.com/2011/07/entity-framework-differed-loading-lazy.html

+0

由於現在工作得很好! – Karb 2012-03-21 12:15:48

+6

@Karb:您可以通過點擊答案中留下的白色複選標記來「接受」答案,以表明答案確實解決了您的問題。 – Slauma 2012-03-21 20:00:08

+0

你用這個爲我節省了不少時間。我忘記做一對夫婦收藏虛擬,甚至沒有想到要檢查。 – lintmouse 2013-05-14 04:03:54

相關問題