Fluent API HasXXX vs WithXXX methods
本文关键字:WithXXX methods vs HasXXX API Fluent | 更新日期: 2023-09-27 18:34:15
我正在研究如何使用流畅的API:
http://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx
它说以下 1-多关系是一回事:
modelBuilder.Entity<Student>()
.HasRequired<Standard>(s => s.Standard)
.WithMany(std => std.Students)
.HasForeignKey(std => std.StdId);
和
modelBuilder.Entity<Standard>()
.HasMany<Student>(std => std.Students)
.WithRequired(s => s.Standard)
.HasForeignKey(s => s.StdId);
从智能感知中,我注意到 HasXXX 方法返回目标类型,而 WithXXX 方法返回父类型。
所以我不明白第一种方法是如何有效的,因为 HasForeignKey 应用于标准而不是学生?
外键应位于"学生"而不是"标准"上。
请开导我。
- 对于第一个,
modelBuilder.Entity<Student>().HasRequired<Standard>(s => s.Standard)
指定学生实体需要 NotNull 标准导航属性,并返回Standard
实体。然后,使用.WithMany(s => s.Students)
指定学生的另一端(表示标准实体)可以在学生集合属性中包含许多Students
。 - 对于第二个,它直截了当。
modelBuilder.Entity<Standard>()
返回Standard
实体,该实体可以在学生集合属性中包含许多Students
。所以你必须使用.HasMany<Student>(std => std.Students)
.这将返回 Student 实体,您必须使用.HasMany<Student>(std => std.Students)
定义该实体的约束