(USING ENTITY FRAMEWORK 4.3 CODE FIRST)
The code is below. I want to actually be able to do something like:
var instanceStudent = new Student2(){...};
var instanceCourse = new Course2(){...};
instanceStudent.Add(instanceCourse);
db.SaveChanges();
…or anything like that, so long as it works. Basically, I currently am a noob at Entity Framework and I want to be able to know how to add an Entity within another Entity while the Junction table has data in it (i know it’s easy on an empty junction table, but i’m stumped on this one)
public class Student2
{
[Key]
public virtual int StudentId { get; set; }
public virtual string StudentName { get; set; }
public virtual ICollection<Enrollment2> Enrollments { get; set; }
}
public class Course2
{
[Key]
public virtual int CourseId { get; set; }
public virtual string CourseName { get; set; }
public virtual ICollection<Enrollment2> Enrollments { get; set; }
}
public class Enrollment2
{
public virtual int StudentId { get; set; }
public virtual int CourseId { get; set; }
public virtual string Grade { get; set; }
public virtual Student2 Student { get; set; }
public virtual Course2 Course { get; set; }
}
public class ManyMany2 : DbContext, IContext
{
public DbSet<Student2> Students { get; set; }
public DbSet<Course2> Courses { get; set; }
public DbSet<Enrollment2> Enrollments { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student2>()
.HasKey(student => student.StudentId);
modelBuilder.Entity<Course2>()
.HasKey(course => course.CourseId);
modelBuilder.Entity<Enrollment2>()
.HasKey(enrollment => new { enrollment.StudentId, enrollment.CourseId });
modelBuilder.Entity<Student2>()
.HasMany(student => student.Enrollments)
.WithRequired()
.HasForeignKey(enrollment => enrollment.StudentId);
modelBuilder.Entity<Course2>()
.HasMany(course => course.Enrollments)
.WithRequired()
.HasForeignKey(enrollment => enrollment.CourseId);
}
public void Run()
{
Database.SetInitializer(new DropCreateDatabaseAlways<ManyMany2>());
var c1 = new Course2() { CourseName = "Spanish" };
var c2 = new Course2() { CourseName = "Science" };
var c3 = new Course2() { CourseName = "History" };
var s1 = new Student2() { StudentName = "JC" };
var s2 = new Student2() { StudentName = "Joe" };
var s3 = new Student2() { StudentName = "Jill" };
}
}
Entity Framework does not support direct many-to-many associations if the join table has a payload. This means you have to do something like this:
You could also do (or similar with Courses) the following: