代码之家  ›  专栏  ›  技术社区  ›  Harald Coppoolse

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

  •  4
  • Harald Coppoolse  · 技术社区  · 9 年前

    MSDN: Entity Framework Fluent API - Relationships :

    而不是两者都有。

    简化:a 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;}
    }
    

    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 .

    // Summary:
    //     Configures the relationship to be required without a navigation property
    //     on the other side of the relationship. The entity type being configured will
    //     be the dependent and contain a foreign key to the principal. The entity type
    //     that the relationship targets will be the principal in the relationship.
    //
    public ForeignKeyNavigationPropertyConfiguration WithRequiredDependent();
    
    modelBuilder.Entity<Student>()
        .HasRequired(student => student.School)
        .WithRequiredDependent();
    

    我需要什么fluent API?

    1 回复  |  直到 9 年前
        1
  •  5
  •   Henk Holterman    9 年前

    我希望我心中有正确的版本:

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