【问题标题】:Code First Entity Framework Many-to-Many relationshipsCode First Entity Framework 多对多关系
【发布时间】:2012-03-21 11:57:35
【问题描述】:

谁能指出我哪里错了!!

我创建了 2 个简单的类,具有多对多的关系。工作正常,所有表格都正确填充。除非我尝试检索任何学生课程,否则不会返回任何内容...

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

【问题讨论】:

    标签: entity-framework ef-code-first many-to-many


    【解决方案1】:

    如果您使用延迟加载,则需要将属性定义为 virtual ,

     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

    【讨论】:

    • @Karb:您可以通过单击答案左侧的白色复选标记来“接受”答案,以表明该答案确实解决了您的问题。
    • 你用这个为我节省了大量的时间。我忘了让几个收藏成为虚拟的,甚至没想过要检查一下。
    猜你喜欢
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    相关资源
    最近更新 更多