The Entity Framework tutorials site has a nice article on configuringmany-to-many relations. In this post, the same case study is implemented on a MySQL database. In addition, the association table has additional useful fields.


There are two tables: Students and Courses which have many-to-many relation. They are associated by a Student Course table. The Student Course table has one additional field – CourseScore. Course Score is the score attained by a student in a course.

Student class

The student class has an Id property, Name property, and a collection of Courses. For this example, Data annotations (via attributes) are used to create the mapping instead of Fluent API.

Course class

The course class has an Id property, Name property, and a collection of Students.

The Course class is similar to the Student class. Both has a virtual collection of StudentCourse.

StudentCourse class

StudentCourse class associates Students and Course classes. It represents the student_course table which has the coursescore field.

The ForeignKey attribute is used to load up the properties – Student and Course.


The following code how the StudentCourse class can be used to retrieve course scores of students along with the course name.

Entity framework makes the code more maintainable and easy to understand.

Configure many-to-many relations in Entity Framework for a MySQL database
Tagged on:

Leave a Reply

Your email address will not be published. Required fields are marked *