1

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");

1 Answer 1

5

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
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.