2014-02-22 50 views
2

使用實體框架的API我總是會遇到以下兩種方法來映射多對多關係嗎?我從來沒有使用第二個選項...有什麼區別?使用實體框架中的Fluent API創建多對多關係

選項1:

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

選項2:

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

究竟是什麼MapLeftKeyMapRightKey嗎?你什麼時候使用它,並獲得什麼好處?

回答

3

在這種情況下使用.Map(...)方法允許您定義聯結表的名稱以及所述聯結表中的列的名稱。 MapLeftKey(string)將設置引用Student的密鑰的聯結表的FK字段的名稱。同樣,MapRightKey(string)設置引用Lesson表的鍵的結點表的FK字段的名稱。更具描述性的用法如下:

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

如果不使用.Map方法,EF將決定如何命名結表和相關的FK列