I had some research on the internet and found this blog post on learn Entity Framework, but after I code it, it seemed it wasn't what I wanted.
As well as the example on the blog, I have Students
and Courses
. But, I don't want my courses to know whether they are related to courses or not (I wouldn't bother either). But, I want each student to have n courses and that each course could be assigned to more than one student.
public class Student
{
public int id {get; set;}
public string name {get; set;}
public ICollection<Course> courses {get;set;} //or another proper container abstraction
}
public class Course
{
public int id {get; set}
public string name {get; set;}
}
So I would query Student
to know its courses. I implemented this, created a migration, run it on a SQL Server database and implemented a little ASP.NET Core API, with CRUD methods. When I added a second Student
that used the same Course
, the first Student
loses its Course
.
Then I implemented the solution the blog suggests:
public class StudentCourse
{
public int student_id {get;set; }
public Student student {get; set; }
public int course_id {get; set; }
public Course course {get; set; }
}
and add to DbContext
this piece of code:
modelBuilder.Entity<StudentCourse>().HasKey(sc => new { sc.SId, sc.CId });
modelBuilder.Entity<StudentCourse>()
.HasOne<Student>(sc => sc.Student)
.WithMany(s => s.StudentCourses)
.HasForeignKey(sc => sc.SId);
modelBuilder.Entity<StudentCourse>()
.HasOne<Course>(sc => sc.Course)
.WithMany(s => s.StudentCourses)
.HasForeignKey(sc => sc.CId);
And Student
and Course
would each have ICollection<StudentCourse>
as members. The problem I found with this approach is that I can't create easily an instance of Student
on my code, because the Student
itself is a member of its member StudentCourse
.
Look in your database. This
public ICollection<Course> courses {get;set;}
Will create a direct FK relationship on Course referencing Student. You're not using your StudentCourse entity at all. Should be
public class Student
{
public int id {get; set;}
public string name {get; set;}
public virtual ICollection<StudentCourse> Courses {get;} = new HashSet<StudentCource>();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.