Many to many relation using Entity Framework Core (Code first)

Here I am going to show step by step – how to create many to many relation using Entity Framework Core.

Step 1 (Create a console application) :

Create a console application named “Many_2_Many_FECore”.

Step 2 (Create classes) :

Lets create two classes named “Teacher” and “Student”, using this two classes I will make many to many relation.

Teacher.cs :

public class Teacher
{
public Teacher()
{
TeacherStudents = new List<TeacherStudent>();
}

public int Id { get; set; }
public string Name { get; set; }
public string Position { get; set; }
public List<TeacherStudent> TeacherStudents{ get; set; }
}

Student.cs :

public class Student
{
public Student()
{
TeacherStudents= new List<TeacherStudent>();
}

public int Id { get; set; }
public string Name { get; set; }
public string Roll { get; set; }
public List<TeacherStudent> TeacherStudents{ get; set; }
}

Now I am going to take another class for many to many relation named “TeacherStudent”.

TeacherStudent.cs :

public class TeacherStudent
{
//See TeacherStudent has no primary key, 
        //but Entity Framework Core wants primary key for this class. I will discuss letter how can        // we solve this.

public int TeacherId { get; set; }
public Teacher Teacher { get; set; }
public int StudentId { get; set; }
public Student Student { get; set; }
}

Step 3 (Add NuGet Packages) :

Right click on project name add select “Manage NuGet Packages” then we can see below window.
Search “Microsoft.EntityFrameworkcore.sqlserver” and click install button. After accept licensee it will install automatically.

Same as install “Microsoft.EntityFrameworkcore.tools” package.

Step 4 (Create context class) :

Create a class named ‘MyContext”.

MyContext.cs :

public class MyContext : DbContext
{
public DbSet<Teacher> Teachers { get; set; }
public DbSet<Student> Students { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//This line use to avoid primary key of TeacherStudent table
modelBuilder.Entity<TeacherStudent>().HasKey(s => new { s.StudentId, s.TeacherId });

            base.OnModelCreating(modelBuilder);
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//New created database name will be DbTeacherStudent
optionsBuilder.UseSqlServer(“Data Source=.;Initial Catalog=DbTeacherStudent;Integrated Security=True”);
}
}

Step 5 :

Now I am going to add a migration,
Select tools => NuGet Package Manager => Package manager console. Like Below :

write add-migration myMigration and click entry.

After that we will see below “Migration” folder.

Step 6 :

Migration done but database is not create yet. To create database we need to write below text and click enter :

“update-database -verbose”

After operation will done, open SqlServer and we will see a new database named “DbTeacherStudent”

Done. 🙂

 

Leave a Reply