Tuesday, December 10, 2013

Configure Many-to-Many relationship

We are going to configure Many-to-Many relationship between Student and Course entity classes.

Configure Many-to-Many relationship using DataAnnotation:

Student class should have collection navigation property for Course and Course should have collection navigation property for student which will create Many-to-Many relationship between student and course as below:
     
    public class Student
    {
        public Student() { }

        public int StudentId { get; set; }
        [Required]
        public string StudentName { get; set; }

        public int StdandardId { get; set; }
        
        public virtual ICollection<Course> Courses { get; set; }
    }
        
    
    public class Course
    {
        public Course()
        {
            this.Students = new HashSet<Student>();
        }

        public int CourseId { get; set; }
        public string CourseName { get; set; }

        public virtual ICollection<Student> Students { get; set; }
    }
        
Above code will create following database where code first will create third joining table CourseStudent which will consist PK of both the tables ie. StudentId & CourseId:

one-to-one relationship in code first

Configure Many-to-Many relationship using Fluent API:

You can use Fluent API to configure Many-to-Many relationship between Student and Course as following:
   
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

       modelBuilder.Entity<Student>().HasMany<Course>(s => s.Courses).WithMany(c => c.Students).Map(c =>
        {
            c.MapLeftKey("Student_id");
            c.MapRightKey("Course_id");
            c.ToTable("StudentAndCourse");
        });

        base.OnModelCreating(modelBuilder);
    }
        
As you can see in above code that we are mapping left key (key column of Student class)with “Student_id” and right key (key column of Course class) with “Course_id” of table "StudentAndCourse".

This will create new joining table “StudentAndCourse” with two PK which is also FK as below:

one-to-one relationship in code first

No comments:

Post a Comment