Many-to-many relationships

When we have a many-to-many relationship, we can say that a record in one table is related to multiple records in another table in a specified relationship, and the other way round is also true. 

An example is a relationship between students and courses.

With Entity Framework Core 3.0, you can't have the Fluent API create a many-to-many relationship directly, but there is a workaround you can use. To do this, we can construct a join table and map the two classes. Let's take a look at how to do this.

Let's say we have a class called Student and a class called Course. With these classes, we can create a StudentCourse table, as follows:

public class Student
{
public long Id { get; set; }
public string Name { get; set; }
public StudentDetails StudentDetails { get; set; }

public ICollection<StudentSubject> StudentSubjects { get; set; }
// Added after constructed table

}

Then, we can have a Course table and a StudentCourse join table, as follows:

public class Course
{
public long Id { get; set; }
public string CourseName { get; set; }

public ICollection<StudentCourse> StudentCourses { get; set; }
// Added after constructed table

}

public class StudentCourse
{
public long StudentId { get; set; }
public Student Student { get; set; }

public long CourseId { get; set; }
public Course Course { get; set; }
}

Now, we can use the Fluent API to represent our many-to-many relationship, as follows:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasKey(s => new { s.StudentId, s.SubjectId });

modelBuilder.HasOne(ss => ss.Student)
.WithMany(s => s.StudentSubjects)
.HasForeignKey(ss => ss.StudentId);

modelBuilder.HasOne(ss => ss.Subject)
.WithMany(s => s.StudentSubjects)
.HasForeignKey(ss => ss.SubjectId);
}

Here, we have made a workaround so that we can have a many-to-many relationship between the student and course entities.

With these relationships, Entity Framework will create the necessary tables when we perform migrations and update the database, but what good is data that just sits in the database? We need to be able to query and utilize it. In the next section, we will talk about working with queries.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.31.26