Question

Using Entity Framework's API I keep coming across the following two ways to map many to many relationships? I have never used the second option... what is the difference?

Option 1:

modelBuilder.Entity<Student>()
    .HasMany( p => p.Lessons)
    .WithMany();

Option 2:

modelBuilder.Entity<Student>()
.HasMany(p => p.Lessons)
.WithMany() 
.Map(m =>
{
    m.MapLeftKey("Id");
    m.MapRightKey("Id");
    m.ToTable("StudentAndLessons");
});

What exactly does MapLeftKey and MapRightKey do? When would you use it and what benefits are gained?

Was it helpful?

Solution

Using the .Map(...) method in this scenario allows you to define the name of the junction table as well as the names of the columns in said junction table. MapLeftKey(string) would set the name of the FK field of the junction table referencing the key for Student. Likewise, MapRightKey(string) sets the name of the FK field of the junction table referencing the key of the Lesson table. A more descriptive usage is as follows:

modelBuilder.Entity<Student>()
    .HasMany(p => p.Lessons)
    .WithMany() 
    .Map(m =>
    {
        m.MapLeftKey("StudentId");
        m.MapRightKey("LessonId");
        m.ToTable("StudentLesson");
    });

Without using the .Map method, EF will decide how to name the junction table and the associated FK columns

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top