This excerpt code successfully creates a many-many relationship with an explicit Junction table that has additional data within it.
PROBLEM: I want to be able to access Courses from Student and vice versa,
(therefore the commented virtual property. But if I uncomment it, it causes an error (see below))
If I don't explicitly create a junction table (no additional data), the virtual keyword works though as EF creates a junction table by convention.
QUESTION:
How can I make Student access Courses without going through Enrollments? Or is that not possible? If it's not possible, then what's the best way to go about this?
(a beginner in EF and C#)
public class Student
{
[Key]
public int StudentId { get; set; }
public string StudentName { get; set; }
//public virtual Course Courses { get; set; }
}
public class Course
{
[Key]
public int CourseId { get; set; }
public string CourseName { get; set; }
//public virtual Student Students { get; set; }
}
public class Enrollment
{
[Key]
public int EnrollmentId { get; set; }
public Student Student { get; set; }
public Course Course { get; set; }
public string Grade { get; set; }
}
public class ManyMany : DbContext, IContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public void Run()
{
Database.SetInitializer(new DropCreateDatabaseAlways<ManyMany1>());
this.Courses.Add(new Course() {CourseName = "English"});
this.SaveChanges();
}
}
WHEN I UNCOMMENT public virtual...
ERROR: "Unable to determine the principal end of an association between the types 'EF.Course' and 'EF.Student'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations."
Entity Framework can't automatically determine 'many-to-many' relations because they are expressed with the help of additional tables in SQL (in your case it is
Enrollment
table). You can specify mappings directly inOnModelCreating
method:Also, take a note that if an entity have many other entities, use collection for relationship:
Older question concerning this, answer and more info here: Entity Framework CodeFirst many to many relationship with additional information.
EDIT: Usage example: