实体框架一对多,只有一个导航属性:WithRequiredDependant?

时间:2017-07-13 08:52:04

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

使用最新的Entity Framework我有一个一对多的类,在很多方面只有一个导航属性。

MSDN: Entity Framework Fluent API - Relationships中所述:

  

单向(也称为单向)关系是a   navigation属性仅在一个关系结束时定义   而不是两者都有。

简化:<div class="image-changing"> <ion-icon name="ios-arrow-back" class="arrow-back"></ion-icon> <ion-icon name="ios-arrow-back" class="arrow-back"></ion-icon> <span class="circle"></span> <ion-icon name="ios-arrow-forward" class="arrow-forward"></ion-icon> <ion-icon name="ios-arrow-forward" class="arrow-forward"></ion-icon> </div>有许多School;学校和学生之间存在一对多的关系,但学校没有包含学生集合的财产

Students

在双向关系中,您可以在class Student { public int Id {get; set;} // a Student attends one School; foreign key SchoolId public int SchoolId {get; set;} public School School {get; set;} } class School { public int Id {get; set;} // missing: public virtual ICollection<Studen> Students {get; set;} } 中编写以下流畅的API:

OnModelCreating

由于缺少protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Student>() .HasRequired(student => student.School) .WithMany(school => school.Students) .HasForeignKey(student => student.SchoolId); } ,我需要做一些额外的事情。根据开头的链接,似乎我必须对School.Students做一些事情。

WithRequiredDependant
唉,这不起作用。 SchoolId没有被建模为外键。

我需要什么样的流畅API?

1 个答案:

答案 0 :(得分:4)

我希望我的版本/版本正确:

modelBuilder.Entity<Student>()
    .HasRequired(student => student.School)
  //.WithMany(school => school.Students)
    .WithMany()
    .HasForeignKey(student => student.SchoolId);