Many-many relationship in Entity Framework Code First and using the “virtual” keyword to access each other

前端 未结 2 1021
夕颜
夕颜 2021-01-06 08:19

This excerpt code successfully creates a many-many relationship with an explicit Junction table that has additional data within it.

PROBLEM:

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-06 08:30

    Entity Framework can't automatically determine 'many-to-many' relations because they are expressed with the help of additional tables in SQL (in your case it is Enrollment table). You can specify mappings directly in OnModelCreating method:

    public class YourDbContext : DbContext
    {
        ....
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity().HasMany(x => x.Courses).WithMany(x => x.Students)
                .Map(m =>
                {
                    m.ToTable("Enrollment"); // Relationship table name
                    m.MapLeftKey("StudentID"); // Name of column for student IDs
                    m.MapRightKey("CourseID"); // Name of column for course IDs
                });
        }
    }
    

    Also, take a note that if an entity have many other entities, use collection for relationship:

    public class Student
    {
        ....
        public virtual ICollection Courses { get; set; } // Many courses
    }
    
    public class Course
    {
        ....
        public virtual ICollection Students { get; set; } // Many students
    }
    

提交回复
热议问题