【问题标题】:EF relationship mapping with Fluent APIEF 关系映射与 Fluent API
【发布时间】:2016-11-01 05:44:27
【问题描述】:

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

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

【问题讨论】:

    标签: c# entity-framework ef-fluent-api


    【解决方案1】:

    您不需要两个 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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-22
      • 1970-01-01
      • 1970-01-01
      • 2019-11-28
      • 2011-10-06
      • 2021-05-01
      • 1970-01-01
      相关资源
      最近更新 更多