Matthew Layton
Matthew Layton

Reputation: 42239

EF relationship mapping with Fluent API

Say for example I have this simple model

class Student
{
    List<Course> Courses { get; set; }
}

class Course
{
    Student Student { get; set; }
}

Do I have to map the relationship in both directions?

Example

builder
    .Set<Course>()
    .HasOne(o => o.Student)
    .WithMany(o => o.Courses)
    .HasForeightKey("StudentId");

builder
    .Set<Student>()
    .HasMany(o => o.Courses)
    .WithOne(o => o.Student)
    .HasForeignKey("StudentId");

Upvotes: 1

Views: 710

Answers (1)

Jared Stroebele
Jared Stroebele

Reputation: 584

You do not need both Fluent Api statements. You are already mapping "both directions" with a single statement.

builder
    .Set<Course>()
    .HasOne(o => o.Student) //Course Has One Student  
    .WithMany(o => o.Courses) //Student Has Many Courses
    .HasForeightKey("StudentId"); //Course Has Foreign Key of StudentId

Here is a good tutorial entity framework tutorial the example there looks like this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //configure one-to-many
    modelBuilder.Entity<Standard>()
                .HasMany<Student>(s => s.Students) //Standard has many Students
                .WithRequired(s => s.Standard)  //Student require one Standard
                .HasForeignKey(s => s.StdId); //Student includes specified foreignkey property name for Standard
}

Upvotes: 5

Related Questions