I have something like a Department, which can have many courses and students. students can be linked to many courses and courses could have many students registered to it. I also want student and courses to be linked to a department.
How can i express this in EF/Fluent API, I have tried these
modelBuilder.Entity<Student>().HasRequired(s => s.Department);
modelBuilder.Entity<Course>().HasRequired(u => u.Department);
modelBuilder.Entity<Course>()
.HasMany(s => s.Students)
.WithOptional()
.WillCascadeOnDelete(false);
modelBuilder.Entity<Course>()
.HasMany(u => u.Students)
.WithMany(s => s.Courses);
modelBuilder.Entity<Student>()
.HasMany(s => s.Courses)
.WithOptional()
.WillCascadeOnDelete(false);
and I tried few other combinations as well, nothing worked and I get this error now
The navigation property 'Courses' declared on type 'Models.Student' has been configured with conflicting multiplicities.
Any hints/ help?
Update: The student class looks like this
public class Student
{
[Key]
public string Id { get; set; }
[Required]
public string SiteName { get; set; }
public virtual Department Department { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
and the Course:
public class Course
{
[Key]
public string Id { get; set; }
[Required]
public string Name { get; set; }
public virtual Department Department { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
That's because in order to do a many-to-many like this you need to create a link table between the tables, which you might call StudentCourses
. Then your Student
and Course
classes would have a collection of type StudentCourse
. Here's how you would create the class (using Data Annotations):
public class StudentCourses
{
[ForeignKey("Student")]
public int StudentID { get; set; }
[ForeignKey("Course")]
public int CourseID { get; set; }
public virtual Student Student { get; set; }
public virtual Course Course { get; set; }
}
Also, if you still want to be able to grab all students in a course (or all courses that a student is taking), you can do it easily using the NotMapped
attribute for a public property to get it as follows:
For your Student
class:
[NotMapped]
public List<Course> Courses {
get { return StudentCourses.Select(sc => sc.Course); }
}
For your Course
class:
[NotMapped]
public List<Student> Students {
get { return StudentCourses.Select(sc => sc.Student); }
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments