EF关系映射与Fluent API

本文关键字:Fluent API 映射 关系 EF | 更新日期: 2023-09-27 18:15:47

比如说我有一个简单的模型

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");

EF关系映射与Fluent API

您不需要两个Fluent Api语句。您已经用一个语句映射了"两个方向"。

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

这是一个很好的实体框架教程,它的例子是这样的:

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
}