Search code examples
entity-frameworkmany-to-many

How to setup custom join table in Entity Framework


When setting up a many-to-many relationship with Code First approach, by default the join table only includes 2 columns (FK to PK of the 2 tables).

1) Is it possible/How can I setup a join table that will include some additional fields, and 2) how do I fill these values via code?

For example:

class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Course> Courses { get; set; }
}

class Course
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Student> Students { get; set; }
}

class MyDbContext : DbContext
{
    public DbSet<Student> Students { get; set; }
    public DbSet<Course> Courses { get; set; }
}

A simple db with Students and Courses with a many-to-many relationship. However for each join Student-Course, I also want a field, for example: PercentComplete, that tracks how far a student is in each course.

How can this be achieved?

Thanks


Solution

  • This is a case for many-to-many relationship with additional information. You will need to create a new entity called, let's say Enrollments. Then, you will need to set 1-to-Many relationships between Student - Enrollment and Course - Enrollment entities.

    public class Student
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public List<Enrollment> Enrollments { get; set; }//each student can have many enrollments
    }
    
    public class Course
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public List<Enrollment> Enrollments { get; set; }//each course can have many enrollments
    }
    
    
    public class Enrollment
    {
        public int EnrollmentId { get; set; }
        public int PercentComplete{ get; set; }
        public Course Course { get; set; } //each single enrollment involves one course
        public Student Student { get; set; } //each single enrollment involves one student
    }
    

    You can find a detailed example here:

    https://practiceaspnet.wordpress.com/2015/11/09/many-to-many-relationships-with-additional-fields/

    https://practiceaspnet.wordpress.com/2015/11/13/displaying-related-entity-in-gridview-entity-framework-code-first/