Back to: Entity Framework Tutorials For Begineers and Professionals
Configure Many-to-Many Relationships in Entity Framework Fluent API
In this article, I am going to discuss how to configure Many-to-Many relationships between two entities using Entity Framework Fluent API with Examples. Please read our previous article where we discussed how to configure One-to-Many relationships between two entities.
How to Configure Many-to-Many Relationships in Entity Framework?
In many-to-many relationships, a row in one table, let’s say TableA can have many matching rows in another table, let’s TableB, and vice versa is also true i.e. a row in TableB can have many matching rows in TableA. In Relational Databases, we can create such kinds of many-to-many relationships by defining a third table, whose primary key consists of the foreign keys from both tableA and tableB. So, here, the Primary Key is a composite Primary key.
Let us understand this with an example. We are going to implement a One-to-Many relationship between the Student and Course Entities. That means one Student can enroll for many Courses and also, one Course can be taken by many students.
In Entity Framework Code First Approach, we can configure the many-to-many relationship between two entities in the following ways.
- By following Conventions
- By using Fluent API Configurations
By following Conventions
Entity Framework 6 includes default conventions for many-to-many relationships and it is very simple and straightforward. You just need to include a collection navigation property at both ends i.e. at both entities. For example, the Student class should have a collection navigation property of Course type, and the Course class should also have a collection navigation property of Student type to create a many-to-many relationship between them without any configuration.
Student.cs
Create a class file with the name Student.cs and then copy and paste the following code into it.
using System.Collections.Generic; namespace EFCodeFirstDemo { public class Student { public Student() { this.Courses = new HashSet<Course>(); } public int StudentId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public virtual ICollection<Course> Courses { get; set; } } }
Course.cs
Create a class file with the name Course.cs and then copy and paste the following code into it.
using System.Collections.Generic; namespace EFCodeFirstDemo { 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; } } }
Next, modify the context class as follows:
using System.Data.Entity; namespace EFCodeFirstDemo { public class EFCodeFirstContext : DbContext { public EFCodeFirstContext() : base("name=MyConnectionString") { //Setting the Database Initializer as DropCreateDatabaseAlways Database.SetInitializer(new DropCreateDatabaseAlways<EFCodeFirstContext>()); } public DbSet<Student> Students { get; set; } public DbSet<Course> Courses { get; set; } } }
Please make sure to have the connection string with the name MyConnectionString within the app.config file or web.config file as shown in the below image.
Next, modify the Main method as follows:
using System; using System.Collections.Generic; namespace EFCodeFirstDemo { class Program { static void Main(string[] args) { using (EFCodeFirstContext context = new EFCodeFirstContext()) { var courses = new List<Course> { new Course() { CourseName = "C#"}, new Course() { CourseName = "ASP.NET Core" } }; context.Courses.AddRange(courses); context.SaveChanges(); Console.WriteLine("Courses Added"); var student = new Student() {FirstName = "Pranaya", LastName = "Rout", Courses = courses}; context.Students.Add(student); context.SaveChanges(); Console.WriteLine("Student Added"); } Console.ReadKey(); } } }
With the above changes in place, run the application and verify the database and you should see the following. The Entity Framework API will create Students, Courses, and the joining table StudentCourses in the database. The StudentCourses table will also include the PK (Primary Key) of both tables – Student_StudentId and Course_CourseId, as shown in the below image.
Note: Entity Framework will automatically create a joining table with the name of both entities and the suffix ‘s’.
Configuring Many-to-Many Relationships using Entity Framework Fluent API
As we have already seen, the default entity framework conventions create a joining table with the default naming conventions for many-to-many relationships. We need to use Entity Framework Fluent API if we want to customize the joining table name and column names.
For a better understanding, modify the context class as follows. In the below example, the HasMany() and WithMany() methods are used to configure many-to-many relationships between the Student and Course entities. The Map() method takes an Action type delegate, hence, we can pass the lambda expression to customize column names in a joining table. We can specify the Primary Key property name of the Student in MapLeftKey() (we started with the Student entity, so it will be the left table) and the Primary Key of the Course table in the MapRightKey() method. The ToTable() method specifies the name of a joining table (StudentCourse in this case).
using System.Data.Entity; namespace EFCodeFirstDemo { public class EFCodeFirstContext : DbContext { public EFCodeFirstContext() : base("name=MyConnectionString") { //Setting the Database Initializer as DropCreateDatabaseAlways Database.SetInitializer(new DropCreateDatabaseAlways<EFCodeFirstContext>()); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Student>() .HasMany<Course>(s => s.Courses) .WithMany(c => c.Students) .Map(cs => { cs.MapLeftKey("StudentReferenceId"); cs.MapRightKey("CourseReferenceId"); cs.ToTable("StudentCourse"); }); } public DbSet<Student> Students { get; set; } public DbSet<Course> Courses { get; set; } } }
With the above changes in place, now run the application and verify the database. Now, it will create a joining table StudentCourse with two Primary Keys StudentReferenceId and CourseReferenceId which will also be Foreign Keys as shown in the below image.
In the next article, I am going to discuss How to Generate Context and Entity Classes from an Existing Database using Entity Framework Code-First Approach with Examples. Here, in this article, I try to explain How to Configure Many-to-Many Relationships between Entities in Entity Framework Fluent API with Examples. I hope you enjoyed this Configure Many-to-Many Relationship using Entity Framework Fluent API article. Please give your valuable feedback and suggestions about this article.