Configure Many-to-Many Relationship in Code-First:

Here, we will learn how to configure Many-to-Many relationship between the Student and Course entity classes. Student can join multiple courses and multiple students can join one Course.

Visit Entity Relationship section to understand how EF manages one-to-one, one-to-many and many-to-many relationships between the entities.

Configure Many-to-Many Relationship using DataAnnotation:

First of all, the Student class should have a collection navigation property of Course type, and the Course class should have a collection navigation property of Student type to create a Many-to-Many relationship, as shown below:

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

    public int StudentId { get; set; }
    [Required]
    public string StudentName { 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; }
}
        

The following is the context class that includes Student and Course entities.

public class SchoolDBContext : DBContext
{
    public SchoolDBContext() : base("SchoolDB-DataAnnotations")
    {
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Course> Courses { get; set; }
        
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

EF API will create Students, Courses and also create joining table StudentCourses in the database for the above example. The StudentCourses table will include PK (Primary Key) of both the tables - Student_StudentId & Course_CourseId, as shown below.

one-to-one relationship in code first

Note: EF automatically creates joining table with the name of the both entities with suffix 's'.

Configure Many-to-Many Relationship using Fluent API:

You can use the Fluent API to configure a Many-to-Many relationship between Student and Course, as shown below:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

    modelBuilder.Entity<Student>()
                .HasMany<Course>(s => s.Courses)
                .WithMany(c => c.Students)
                .Map(cs =>
                        {
                            cs.MapLeftKey("StudentRefId");
                            cs.MapRightKey("CourseRefId");
                            cs.ToTable("StudentCourse");
                        });

}
        

As you can see in the above example, .HasMany<Course>(s => s.Courses).WithMany(c => c.Students) says that Student and Course has many-to-many relationship with Students navigation property in Course class and Courses navigation property in Student class.

Map method takes Action type delegate, hence, we can pass lambda expression wherein we will specify FK property name of Student (we start with Student entity, so it will be left table) and FK of Course table. ToTable will create StudentCourse table.

This will create a new joining table StudentCourse with two Primary Keys which will also be Foreign Keys, as shown below:

one-to-one relationship in code first

Note: Please notice that the name of the joining table is specified in the ToTable() method in the Map() function above.


Test Your Entity Framework Knowledge: