创建许多人在实体框架用流利的API许多关系 [英] Creating Many To Many Relationships using Fluent API in Entity Framework
问题描述
使用实体框架的API我不断遇到下列两种方式来映射多对多的关系?我从来没有使用第二个选项...有什么区别
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?
选项1:
modelBuilder.Entity<Student>()
.HasMany( p => p.Lessons)
.WithMany();
选项2:
Option 2:
modelBuilder.Entity<Student>()
.HasMany(p => p.Lessons)
.WithMany()
.Map(m =>
{
m.MapLeftKey("Id");
m.MapRightKey("Id");
m.ToTable("StudentAndLessons");
});
到底是什么 MapLeftKey
和 MapRightKey
吗?当你使用它,并得到了什么好处?
What exactly does MapLeftKey
and MapRightKey
do? When would you use it and what benefits are gained?
推荐答案
使用 .MAP(...在这种情况下)
方法允许您定义结表的名称以及列在上述路口表中的名称。 MapLeftKey(串)
将设置结表引用了学生
键的FK字段的名称。同样, MapRightKey(串)
设置结合表引用课的关键
表的FK字段的名称。一个更具描述性的用法如下:
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");
});
如果不使用 .MAP
方法,EF将决定如何命名结表和相关的FK列
Without using the .Map
method, EF will decide how to name the junction table and the associated FK columns
这篇关于创建许多人在实体框架用流利的API许多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!