Reputation: 101
I am using Code First appraoch in my MVC project. Just for simplicity I have got two classes Course
and Modules
where there is a many to many relationship between the entities. Here is the structure of my classes
public class Course
{
public int CourseId { get; set; }
public string Title { get; set; }
public virtual ICollection<Module> Modules { get; set;
}
public class Module
{
public int ModuleId { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
public virtual ICollection<Course> Courses {get;set;
}
I created two controllers for each using EntityFramework where each controller creates the table for each class. Now having the many to many relationship the EF is smart enough to create the third junction table for me ie. CourseModule(FK_Course_ID, FK_ModuleID)
. But the problem is this table is not get populated with the keys from the respective tables. It is blank. Can anyone please help me how can I figure it out??
Thanks.
Upvotes: 2
Views: 465
Reputation: 5596
I am going out on a limb here but do you have the following in your context class:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Course>()
.HasMany(s => s.Modules)
.WithMany(a => a.Courses)
.Map(m =>
{
m.MapLeftKey("CourseID");
m.MapRightKey("ModuleID");
m.ToTable("CourseModules");
});
}
Also, can we see your code where you try to save Course / Module?
Upvotes: 1