Creating Many To Many Relationships using Fluent API in Entity Framework

会有一股神秘感。 提交于 2019-12-02 06:04:53

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/21954520/creating-many-to-many-relationships-using-fluent-api-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!