Configure Many-to-Many relationship using Fluent API in Entity Framework Core

Configure Many-to-Many relationship using Fluent API in Entity Framework Core

Lets configure Many-to-Many Relationship using Fluent API. Note that there are no default conventions in Entity Framework Core to automatically configure a many-to-many relationship. Therefore you must configure it using Fluent API.

The 2 entities

Consider the 2 entity classes – ‘Student’ & ‘Teacher’.

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class Teacher
{
    public int Id { get; set; }
    public string Name { get; set; }
}

To create a Many-to-Many relationship using Fluent API you have to create a Joining Entity. I name this joining entity as – ‘Teacher Student’.

many to many relationship

Many-to-Many relationship between the ‘Student’ & ‘Teacher’ entities will mean – ‘one student can have many teaches’ and at the same time ‘one teacher can have many students’.

This joining entity will contain the foreign keys (reference navigation property) for both the other entities. These foreign keys will form the composite primary key for this joining entity.

The Teacher Student entity is given below.

public class TeacherStudent
{
    public Student Student { get; set; }
    public Teacher Teacher { get; set; }
}

The steps for configuring many-to-many relationships are as follows:

1. Add foreign key property to other entities, in the joining entity.

public class TeacherStudent
{
    public int StudentId { get; set; } //foreign key property
    public Student Student { get; set; } //Reference navigation property

    public int TeacherId { get; set; } //foreign key property
    public Teacher Teacher { get; set; } //Reference navigation property
}

2. Add collection navigation property on the other entities towards the joining entity.

public class Student
{
    public int Id { get; set; }

    public string Name { get; set; }

    public IList<TeacherStudent> TeacherStudent { get; set; } //collection navigation property
}
public class Teacher
{
    public int Id { get; set; }

    public string Name { get; set; }

    public IList<TeacherStudent> TeacherStudent { get; set; } //collection navigation property
}

3. Configure both the foreign keys in the joining entity as a composite key using Fluent API. Do this in the OnModelCreating() method.

modelBuilder.Entity<TeacherStudent>().HasKey(t => new { t.StudentId, t.TeacherId });

4. Create one-to-many relationship using Fluent API between the joining entity and other entities inside the OnModelCreating() method.

modelBuilder.Entity<TeacherStudent>()
            .HasOne(t => t.Student)
            .WithMany(t => t.TeacherStudent)
            .HasForeignKey(t => t.StudentId);


modelBuilder.Entity<TeacherStudent>()
            .HasOne(t => t.Teacher)
            .WithMany(t => t.TeacherStudent)
            .HasForeignKey(t => t.TeacherId);

On migration you will get the Many-to-Many relationship created as shown in the below image:

composite primary key

The full code of context class is:
public class CompanyContext : DbContext
{
    public DbSet<Teacher> Teacher { get; set; }
    public DbSet<Student> Student { get; set; }
    public DbSet<TeacherStudent> TeacherStudent { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(@"Server=vaio;Database=Company;Trusted_Connection=True;");
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //Write Fluent API configurations here

        modelBuilder.Entity<TeacherStudent>().HasKey(t => new { t.StudentId, t.TeacherId });

        modelBuilder.Entity<TeacherStudent>()
                    .HasOne(t => t.Student)
                    .WithMany(t => t.TeacherStudent)
                    .HasForeignKey(t => t.StudentId);


        modelBuilder.Entity<TeacherStudent>()
                    .HasOne(t => t.Teacher)
                    .WithMany(t => t.TeacherStudent)
                    .HasForeignKey(t => t.TeacherId);
    }
}

DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.