Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C#

Creating a Many To Many Mapping Using Code First

Rate me:
Please Sign up or sign in to vote.
4.83/5 (24 votes)
1 Aug 2011CPOL2 min read 159.2K   26   19
How to create a many to many mapping using Entity Framework Code First for an existing database.

Introduction

Creating a Many To Many Mapping Using Code First

Today, I got a question about how to create a many to many mapping using Entity Framework Code First. The question was how to create the mapping with an existing database. Here is an explanation of how to achieve that.

Creating a Many To Many Mapping

Sometimes, there is a need to create a many to many relation in the database. When we want to achieve that, we create a relation table which will hold the primary key from every table in the many to many relation. Here is an example of a simple many to many relations that can exist in a database:

DatabaseDiagram

In Code First, when we want to create such a relation, all we have to do is create the relevant entities which will hold an ICollection on each side of the relation and create the relevant DbContext. Here is an example for a many to many relation in Code First:

C#
public class Person
{
  public int PersonId { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }

  public ICollection<Course> CoursesAttending { get; set; }

  public Person()
  {
    CoursesAttending = new HashSet<Course>();
  }
}

public class Course
{
  public int CourseId { get; set; }
  public string Title { get; set; }

  public ICollection<Person> Students { get; set; }

  public Course()
  {
    Students = new HashSet<Person>();
  }
}

public class SchoolContext : DbContext
{
  public DbSet<Course> Courses { get; set; }
  public DbSet<Person> People { get; set; }

  public SchoolContext()
    : base("MyDb")
  {
  }
}

Simple as that. The problem starts when we have an existing database where the column names or the relation names aren’t generated by the Code First convention engine. In the previous figure of the database, Code First will generate the column names Person_PersonId and Course_CourseId which don’t match the existing table.

Using the Code First Fluent API to Create a Many To Many Relation Mapping

So we have a small problem with existing relation tables. We can solve the problem by overriding the OnModelCreating method and adding the mapping using the Code First Fluent API. Here is an example of such a mapping to solve the previous model’s problem:

C#
public class SchoolContext : DbContext
{
  public DbSet<Course> Courses { get; set; }
  public DbSet<Person> People { get; set; }

  public SchoolContext()
    : base("MyDb")
  {
  }

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Entity<Course>().
      HasMany(c => c.Students).
      WithMany(p => p.CoursesAttending).
      Map(
       m =>
       {
         m.MapLeftKey("CourseId");
         m.MapRightKey("PersonId");
         m.ToTable("PersonCourses");
       });
  }
}

In OnModelCreating, you will use HasMany to indicate that a course has many students and WithMany to indicate that a person can attend a lot of courses. The Map method will tell Code First how to build the relation table with the relevant name (using a ToTable mapping) and with the relevant keys (MapLeftKey and MapRightKey).

Summary

Creating a many to many relation with Code First is easy. You need to get used to the Fluent API if you have an existing database but the API is self explanatory so it makes your job easier.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead sparXys
Israel Israel
Gil Fink is a web development expert and ASP.Net/IIS Microsoft MVP. He is the founder and owner of sparXys. He is currently consulting for various enterprises and companies, where he helps to develop Web and RIA-based solutions. He conducts lectures and workshops for individuals and enterprises who want to specialize in infrastructure and web development. He is also co-author of several Microsoft Official Courses (MOCs) and training kits, co-author of "Pro Single Page Application Development" book (Apress) and the founder of Front-End.IL Meetup. You can read his publications at his website: http://www.gilfink.net

Comments and Discussions

 
QuestionI know sir this will be the silly question to ask you, but can we add multiple inputs for single "ID" or "Model" or "Make" Pin
Member 1332196921-Jul-17 4:19
Member 1332196921-Jul-17 4:19 
GeneralMy vote of 1 Pin
abbasmhd24-Sep-14 0:25
abbasmhd24-Sep-14 0:25 
GeneralRe: My vote of 1 Pin
Gil Fink24-Sep-14 0:48
Gil Fink24-Sep-14 0:48 
For you it might be basic but to others this post is helpful (take a look at other votes...)
GeneralMy vote of 5 Pin
wowrainyman9-Jul-13 8:54
wowrainyman9-Jul-13 8:54 
QuestionInsert not working Pin
Arsalan Ahmad4-Jul-13 22:53
Arsalan Ahmad4-Jul-13 22:53 
GeneralMy vote of 5 Pin
Mark Heath25-Feb-13 11:43
Mark Heath25-Feb-13 11:43 
GeneralRe: My vote of 5 Pin
Gil Fink1-Mar-13 2:36
Gil Fink1-Mar-13 2:36 
GeneralMy vote of 5 Pin
Illia Ratkevych31-Jan-13 4:23
Illia Ratkevych31-Jan-13 4:23 
GeneralRe: My vote of 5 Pin
Gil Fink1-Mar-13 2:37
Gil Fink1-Mar-13 2:37 
Questionmany to many Pin
marouprod12-Apr-12 12:03
marouprod12-Apr-12 12:03 
AnswerRe: many to many Pin
Gil Fink13-Apr-12 1:16
Gil Fink13-Apr-12 1:16 
QuestionInserts, etc... Pin
Phenomin28-Jan-12 12:18
Phenomin28-Jan-12 12:18 
AnswerRe: Inserts, etc... Pin
Gil Fink29-Jan-12 19:56
Gil Fink29-Jan-12 19:56 
GeneralRe: Inserts, etc... Pin
Member 121919114-Feb-12 4:31
Member 121919114-Feb-12 4:31 
QuestionRe: Inserts, etc... Pin
BMSMA23-Jan-13 21:55
BMSMA23-Jan-13 21:55 
QuestionRelationship table with extra columns Pin
Member 22981063-Nov-11 9:13
Member 22981063-Nov-11 9:13 
AnswerRe: Relationship table with extra columns Pin
Gil Fink5-Nov-11 1:32
Gil Fink5-Nov-11 1:32 
GeneralRe: Relationship table with extra columns Pin
Member 229810614-Nov-11 4:59
Member 229810614-Nov-11 4:59 
GeneralRe: Relationship table with extra columns Pin
RBS219-Nov-12 6:58
RBS219-Nov-12 6:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.