EF 与 Fluent 的关系映射 API
EF relationship mapping with Fluent API
比如说我有这个简单的模型
class Student
{
List<Course> Courses { get; set; }
}
class Course
{
Student Student { get; set; }
}
我必须在两个方向映射关系吗?
例子
builder
.Set<Course>()
.HasOne(o => o.Student)
.WithMany(o => o.Courses)
.HasForeightKey("StudentId");
builder
.Set<Student>()
.HasMany(o => o.Courses)
.WithOne(o => o.Student)
.HasForeignKey("StudentId");
您不需要两个 Fluent Api 语句。您已经在使用单个语句映射 "both directions"。
builder
.Set<Course>()
.HasOne(o => o.Student) //Course Has One Student
.WithMany(o => o.Courses) //Student Has Many Courses
.HasForeightKey("StudentId"); //Course Has Foreign Key of StudentId
这是一个很好的教程entity framework tutorial那里的例子是这样的:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//configure one-to-many
modelBuilder.Entity<Standard>()
.HasMany<Student>(s => s.Students) //Standard has many Students
.WithRequired(s => s.Standard) //Student require one Standard
.HasForeignKey(s => s.StdId); //Student includes specified foreignkey property name for Standard
}
比如说我有这个简单的模型
class Student
{
List<Course> Courses { get; set; }
}
class Course
{
Student Student { get; set; }
}
我必须在两个方向映射关系吗?
例子
builder
.Set<Course>()
.HasOne(o => o.Student)
.WithMany(o => o.Courses)
.HasForeightKey("StudentId");
builder
.Set<Student>()
.HasMany(o => o.Courses)
.WithOne(o => o.Student)
.HasForeignKey("StudentId");
您不需要两个 Fluent Api 语句。您已经在使用单个语句映射 "both directions"。
builder
.Set<Course>()
.HasOne(o => o.Student) //Course Has One Student
.WithMany(o => o.Courses) //Student Has Many Courses
.HasForeightKey("StudentId"); //Course Has Foreign Key of StudentId
这是一个很好的教程entity framework tutorial那里的例子是这样的:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//configure one-to-many
modelBuilder.Entity<Standard>()
.HasMany<Student>(s => s.Students) //Standard has many Students
.WithRequired(s => s.Standard) //Student require one Standard
.HasForeignKey(s => s.StdId); //Student includes specified foreignkey property name for Standard
}