我是否需要用 Fluent API 配置与 Entity Framework 的关系的双方?

Do I need to configure both sides of a relationship with Entity Framework with Fluent API?

我是 Fluent API 的新手。在我的场景中,一个 Student 可以在一个 Grade 中,一个 Grade 可以有多个 Students。然后,这两个语句完成相同的事情:

modelBuilder
.Entity<Student>()
.HasRequired<Grade>(s => s.Grade)
.WithMany(s => s.Students);

并且:

modelBuilder
.Entity<Grade>()
.HasMany<Student>(s => s.Students)
.WithRequired(s => s.Grade);

我的问题是 - 我应该如何选择一种说法而不是另一种说法?还是我需要两个声明?

你只需要一个。这对于1 : M关系来说已经绰绰有余了。

modelBuilder.Entity<Student>()
            .HasRequired<Grade>(s => s.Grade) //Student entity requires Grade 
            .WithMany(s => s.Students); //Grade entity includes many Students entities

对于像你这样的双向关系(即当两端都有导航属性时),这并不重要,你可以使用一个或另一个(你也可以同时使用两者,但不推荐这样做,因为它是多余的,可能会导致两者之间不同步。

当你有 单向 关系时它真的很重要,因为只有 With 方法有无参数重载。

假设您没有 Grade.Students 属性。那么你只能使用:

modelBuilder.Entity<Student>()
    .HasRequired(s => s.Grade)
    .WithMany();

如果您没有Student.Grade 属性,那么您只能使用:

modelBuilder.Entity<Grade>()
    .HasMany(s => s.Students)
    .WithRequired();