Using the newest Entity Framework I have a class with a one-to-many wit only one navigation property on the many side.
As stated in MSDN: Entity Framework Fluent API - Relationships:
A one-directional (also called unidirectional) relationship is when a navigation property is defined on only one of the relationship ends and not on both.
Simplified: a School
has many Students
; there is a one-to-many relation between School and Student, but the School doesn't have a property containing the collection of 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;}
}
In a two-directional relationship, you could write the following fluent API in OnModelCreating
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>()
.HasRequired(student => student.School)
.WithMany(school => school.Students)
.HasForeignKey(student => student.SchoolId);
}
Because of the lack of School.Students
, I need to do something extra. According to the link at the beginning it seems that I'd have to do something with 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();
Alas, this doesn't work. SchoolId is not modeled as the foreign key.
What fluent API do I need?