c# - EF 关系映射与 Fluent API

标签 c# entity-framework ef-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 语句。您已经在用一条语句映射“双向”。

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/

相关文章:

asp.net-mvc - 如何创建查找表并定义关系

c# - 具有两个独立表和一个从属表的多个一对一关系

c# - 使用 Entity Framework Code First 和 Fluent API 配置许多一对一关系

c# - 调用 string 或 in within within if 或 try from outside

linq - 使用连接表的 Automapper 和 Linq,填充 ViewModel 属性

c# - 使用变量调用方法

c# - Code First - 自引用一对多关系

c# - Intellitest 是否可用于 .NET 标准库?

c# - 实体属性值 (EAV) 框架?

c# - 将数据网格列转换为超链接