Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Creating a Many To Many Mapping Using Code First

, 1 Aug 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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 relation 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 in each side of the relation and create the relevant DbContext. Here is an example for a many to many relation in Code First:

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 to 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:

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)

Share

About the Author

Gil Fink
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
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
GeneralMy vote of 1 Pinmemberabbasmhd24-Sep-14 1:25 
GeneralRe: My vote of 1 PinmemberGil Fink24-Sep-14 1:48 
GeneralMy vote of 5 Pinmemberwowrainyman9-Jul-13 9:54 
QuestionInsert not working PinmemberArsalan Ahmad4-Jul-13 23:53 
GeneralMy vote of 5 PinmemberMark Heath25-Feb-13 12:43 
very helpful, thanks
GeneralRe: My vote of 5 PinmemberGil Fink1-Mar-13 3:36 
GeneralMy vote of 5 Pinmembereinstein's brain31-Jan-13 5:23 
GeneralRe: My vote of 5 PinmemberGil Fink1-Mar-13 3:37 
Questionmany to many Pinmembermarouprod12-Apr-12 13:03 
AnswerRe: many to many PinmemberGil Fink13-Apr-12 2:16 
QuestionInserts, etc... PinmemberPhenomin28-Jan-12 13:18 
AnswerRe: Inserts, etc... PinmemberGil Fink29-Jan-12 20:56 
GeneralRe: Inserts, etc... PinmemberMember 121919114-Feb-12 5:31 
QuestionRe: Inserts, etc... PinmemberBMSMA23-Jan-13 22:55 
QuestionRelationship table with extra columns PinmemberMember 22981063-Nov-11 10:13 
AnswerRe: Relationship table with extra columns PinmemberGil Fink5-Nov-11 2:32 
GeneralRe: Relationship table with extra columns PinmemberMember 229810614-Nov-11 5:59 
GeneralRe: Relationship table with extra columns PinmemberRBS219-Nov-12 7:58 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1411023.1 | Last Updated 1 Aug 2011
Article Copyright 2011 by Gil Fink
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid