Home > Mobile >  Can Refer a M-M table inside another table in asp .net core
Can Refer a M-M table inside another table in asp .net core

Time:11-17

I have Student, Teacher, Subject tables.

Teacher and Subject have a M-M relationship

public class TeacherSubject
{
    public int TeacherId { get; set; }
    public Teacher Teacher { get; set; }

    public int SubjectId { get; set; }
    public Subject Subject { get; set; }
}


builder.Entity<TeacherSubject>()
       .HasKey(i => new
           {
               i.SubjectId,
               i.TeacherId
           });

builder.Entity<TeacherSubject>()
       .HasOne(i => i.Subject)
       .WithMany(i => i.TeacherSubjects)
       .HasForeignKey(i => i.SubjectId);

builder.Entity<TeacherSubject>()
       .HasOne(i => i.Teacher)
       .WithMany(i => i.TeacherSubjects)
       .HasForeignKey(i => i.TeacherId);

Student can choose multiple subject, each subject can have multiple teacher.

Student A , B
Subject - C, D
Teacher - X, y, Z

Subject C can teach by Teacher X, Teacher Y

So Student A - take Subject C which is taught by Teacher X.

Now can I refer to the TeacherSubject table inside student?

public class Student
{
    public List<TeacherSubject> TeacherSubjects { get; set; }

    // rest 
}

Please anyone guide me.

CodePudding user response:

you again need a many-to-many relationship between the student and subject-teacher mapping, because the same subject-teacher combination is applicable to many students.

so it would help if you had a separate table which should have studentid and subject-teacherid.

suppose you add the studentid column to student-teacher table. it will bring redundant data.

  • Related