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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Selva GanapathyPosted Feb 24, 2014, 12:40 AM
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
Jaganathan BantheswaranPosted Feb 24, 2014, 12:32 AM
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; }
}