gpt4 book ai didi

c# - EF 关系映射与 Fluent API

转载 作者:太空宇宙 更新时间:2023-11-03 19:50:17 27 4
gpt4 key购买 nike

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

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 语句。您已经在用一条语句映射“双向”。

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
}

关于c# - EF 关系映射与 Fluent API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40350176/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com