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

C# 实体框架一对多,只有一个导航属性:WithRequiredDependant?,c#,entity-framework,ef-fluent-api,C#,Entity Framework,Ef Fluent Api,使用最新的实体框架,我有一个一对多的类,在多个方面只有一个导航属性 如下列文件所述: 单向(也称为单向)关系是指 导航属性仅在关系的一个端点上定义 而不是两者都有 简化:一所学校有许多学生;学校和学生之间存在一对多关系,但学校没有包含学生集合的属性 class Student { public int Id {get; set;} // a Student attends one School; foreign key SchoolId public int School

使用最新的实体框架,我有一个一对多的类,在多个方面只有一个导航属性

如下列文件所述:

单向(也称为单向)关系是指 导航属性仅在关系的一个端点上定义 而不是两者都有

简化:一所
学校
有许多
学生
;学校和学生之间存在一对多关系,但学校没有包含学生集合的属性

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;}
}
由于缺少学校。学生们,我需要做些额外的事情。根据开头的链接,似乎我必须使用RequiredDependant来处理

// 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();
//摘要:
//将关系配置为不带导航属性的必需关系
//在关系的另一边。正在配置的实体类型将
//是从属项并包含主体的外键。实体类型
//关系目标将是关系中的主体。
//
public ForeignKeyNavigationPropertyConfiguration with RequiredDependent();
modelBuilder.Entity()
.has必填项(学生=>student.School)
.WithRequiredDependent();
唉,这行不通。SchoolId未建模为外键


我需要什么样的fluent API?

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

modelBuilder.Entity<Student>()
    .HasRequired(student => student.School)
  //.WithMany(school => school.Students)
    .WithMany()
    .HasForeignKey(student => student.SchoolId);
modelBuilder.Entity()
.has必填项(学生=>student.School)
//.WithMany(school=>school.Students)
.有很多
.HasForeignKey(学生=>student.SchoolId);

您是否尝试使用RequiredPrincipal
而不是RequiredDependent
?“使用最新的…”-最好弄清楚确切的版本以及它是否是核心版本。这个问题在几个月后应该还是有意义的。当然,我试过了两种方法,都是必需的…,我并没有提到,因为问题已经很长了。使用“最新版本”意味着我准备更新到我需要的任何版本,以避免出现类似“如果您要升级到版本…您可以使用…”这样的回答:WithMany()不带参数!它与RequiredPrincipal和RequiredDependant无关。我发现它用于required:required关系(是一对一吗?)
modelBuilder.Entity<Student>()
    .HasRequired(student => student.School)
  //.WithMany(school => school.Students)
    .WithMany()
    .HasForeignKey(student => student.SchoolId);