Creating Many To Many Relationships using Fluent API in Entity Framework
Asked Answered
M

1

2

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?

Midget answered 22/2, 2014 at 12:45 Comment(0)
V
5

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

Vuillard answered 22/2, 2014 at 13:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.