Many to many relationship in MVC
I am new to MVC application code first using entity framework. How to make many to many relationship in MVC..I am having more than 3 fields in joining table..please help me.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Jaganathan BantheswaranRank #170 · 14.1K reputationPosted Feb 23, 2014, 7:32 PM EST
Consider you have Student & Course models in your project.
public class Student
{
[Key]
public int studentId {get; set;}
public List courses {get; set;} // Many courses
}
public class Course
{
[Key]
public int courseId {get; set;}
public List students {get; set;} // Many Students
}
Next, go to your DB Context class which you derived from DBContext.
It can be something
public class CourseDBContext : DbContext
{
public CourseDBContext() : base("DemoDBConnection")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// M2M relations from Student to Course.
modelBuilder.Entity()x
.HasMany(c => c.courses)
.WithMany(s => s.students)
.Map (mc =>
{
mc.ToTable("StudentCourse");
mc.MapLeftKey("courseId");
mc.MapRightKey("studentId");
});
}
public DbSet Students { get; set; }
public DbSet Courses { get; set; }
}
Selva GanapathyRank #560 · 4.3K reputationPosted Feb 23, 2014, 7:40 PM EST
Using the following code you can handle and add many to many relationship in MVC.
protected override void Seed(MVC4PartialViewsContext tamil)
{
base.Seed(tamil);
var item1 = new Course { ItemID = 1, ItemDescripcion = "Tamil is a classical language" };
var item2 = new Course { ItemID = 2, ItemDescripcion = "Tamil has great literature" };
var item3 = new Course { ItemID = 3, ItemDescripcion = "Tamil is a great language" };
tamil.Courses.Add(item1);
tamil.Courses.Add(item2);
tamil.Courses.Add(item3);
}
Regards,
Selva Ganapathy K