在Entity Framework中使用Fluent API创建多对多关系
使用Entity Framework的API我会不断发现以下两种方式来映射多对多的关系? 我从未使用过第二种选择……有什么区别?
选项1:
modelBuilder.Entity() .HasMany( p => p.Lessons) .WithMany();
选项2:
modelBuilder.Entity() .HasMany(p => p.Lessons) .WithMany() .Map(m => { m.MapLeftKey("Id"); m.MapRightKey("Id"); m.ToTable("StudentAndLessons"); });
MapLeftKey
和MapRightKey
做了什么? 你何时会使用它并获得了哪些好处?
在此方案中使用.Map(...)
方法允许您定义联结表的名称以及所述联结表中列的名称。 MapLeftKey(string)
将设置引用表的FK字段的名称,引用Student
的键。 同样, MapRightKey(string)
设置引用表的FK字段的名称,引用Lesson
表的键。 更具描述性的用法如下:
modelBuilder.Entity() .HasMany(p => p.Lessons) .WithMany() .Map(m => { m.MapLeftKey("StudentId"); m.MapRightKey("LessonId"); m.ToTable("StudentLesson"); });
不使用.Map
方法,EF将决定如何命名联结表和关联的FK列