Code First Entity Framework Many-to-Many relationships

こ雲淡風輕ζ 提交于 2019-12-07 15:22:17

问题


Can someone point out where I've got wrong!!

I have created 2 simple classes, with many-to-many relationship. Works fine, all the tables are populated correctly. Except when I try and retrive any Students courses nothing is returned...

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);
                }
            }

回答1:


If you are using lazy loading you need to defiine properties as virtual ,

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

and if you want you can use eager loading,

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

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



来源:https://stackoverflow.com/questions/9804175/code-first-entity-framework-many-to-many-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!