Har*_*lse 4 c# entity-framework ef-fluent-api
使用最新的实体框架,我有一个一对多的类,在多方面只有一个导航属性。
如MSDN 中所述:Entity Framework Fluent API - Relationships:
单向(也称为单向)关系是指仅在关系的一个端点上而不是在两个端点上定义导航属性。
简化:aSchool
有很多Students
;School 和 Student 之间存在一对多关系,但 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;}
}
Run Code Online (Sandbox Code Playgroud)
在双向关系中,您可以在 中编写以下流畅的 API OnModelCreating
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>()
.HasRequired(student => student.School)
.WithMany(school => school.Students)
.HasForeignKey(student => student.SchoolId);
}
Run Code Online (Sandbox Code Playgroud)
由于缺少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();
Run Code Online (Sandbox Code Playgroud)
唉,这行不通。SchoolId 未建模为外键。
我需要什么流畅的 API?
我希望我有正确的版本/版本:
modelBuilder.Entity<Student>()
.HasRequired(student => student.School)
//.WithMany(school => school.Students)
.WithMany()
.HasForeignKey(student => student.SchoolId);
Run Code Online (Sandbox Code Playgroud)