2

Currently in my code I am doing something like this

public class Subject
{
    private List<Subject> _prerequisites;
}

A subject can have many prerequisites (which are also subjects), and subject can be a prerequisite of many subjects.

We were originally using typed datasets to save the data to the database and our tables looked like this:

DatabaseDiagram

We now want to migrate from using typed datasets to entity framework but I'm not sure how to create the mapping. Generating the EF from the database doesn't really work as it just drops each table and uses the foreign keys as navigation properties. From what I understand EF doesn't need another entity for a many to many relationship. If anyone can help, that would be great! Cheers!

Jason King
  • 265
  • 1
  • 4
  • 19

1 Answers1

2

Figured it out. Needed to override the default model building of this in the OnModelCreating method in the class that inherits the DbContext.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Subject>().
        HasMany(m => m.Prerequisites).
        WithMany()
        .Map(m =>
            {
                m.ToTable("SubjectPrerequisite");
                m.MapLeftKey("SubjectId");
                m.MapRightKey("PrerequisiteId");
            });
}
Jason King
  • 265
  • 1
  • 4
  • 19