C# 在实体框架中使用Fluent API创建多对多关系
使用实体框架的API,我经常遇到以下两种映射多对多关系的方法?我从未使用过第二种选择。。。有什么区别 备选案文1:C# 在实体框架中使用Fluent API创建多对多关系,c#,entity-framework,fluent-interface,C#,Entity Framework,Fluent Interface,使用实体框架的API,我经常遇到以下两种映射多对多关系的方法?我从未使用过第二种选择。。。有什么区别 备选案文1: modelBuilder.Entity<Student>() .HasMany( p => p.Lessons) .WithMany(); modelBuilder.Entity() .HasMany(p=>p.Lessons) .有许多(); 备选案文2: modelBuilder.Entity<Student>() .HasMa
modelBuilder.Entity<Student>()
.HasMany( p => p.Lessons)
.WithMany();
modelBuilder.Entity()
.HasMany(p=>p.Lessons)
.有许多();
备选案文2:
modelBuilder.Entity<Student>()
.HasMany(p => p.Lessons)
.WithMany()
.Map(m =>
{
m.MapLeftKey("Id");
m.MapRightKey("Id");
m.ToTable("StudentAndLessons");
});
modelBuilder.Entity()
.HasMany(p=>p.Lessons)
.有很多
.Map(m=>
{
m、 MapLeftKey(“Id”);
m、 MapRightKey(“Id”);
m、 ToTable(“学生和教师”);
});
MapLeftKey
和MapRightKey
到底做什么?您将在何时使用它以及获得什么好处?在此场景中使用.Map(…)
方法允许您定义连接表的名称以及所述连接表中列的名称MapLeftKey(string)
将设置引用Student
键的连接表的FK字段的名称。同样,MapRightKey(string)
设置连接表的FK字段的名称,该字段引用课程
表的键。更具描述性的用法如下:
modelBuilder.Entity<Student>()
.HasMany(p => p.Lessons)
.WithMany()
.Map(m =>
{
m.MapLeftKey("StudentId");
m.MapRightKey("LessonId");
m.ToTable("StudentLesson");
});
modelBuilder.Entity()
.HasMany(p=>p.Lessons)
.有很多
.Map(m=>
{
m、 MapLeftKey(“学生ID”);
m、 MapRightKey(“莱索尼德”);
m、 ToTable(“学生课”);
});
如果不使用.Map
方法,EF将决定如何命名连接表和关联的FK列