0

I have to classes:

public class Subject

{
    [Key]
    public int SubjectID { get; set; }

    public string SubjectName { get; set; }

    public virtual ICollection<Teacher> Teachers { get; set; }


}

and

public class Teacher

{
    [Key]
    public int TeacherID { get; set; }

    public string TeacherName { get; set; }

    public virtual ICollection<Subject> Subjects { get; set; }

}

So I created the many to many relationship between the two tables and the EF will automatically create the junction table:

SubjectTeachers:

PK SubjectID

PK TeacherID

My question is, how do I tell the EF to how to link the values inside the tables?

Example:

SubjectID = 1; SubjectName = Math;

SubjectID = 2; SubjectName = Biology;

TeacherID = 1; TeacherName = MathTeacher;

TeacherID = 2; TeacherName = MathTeacher2;

TeacherID = 3; TeacherName = BiologyTeacher;

How can I specify in the DbInitializer when seeding data, that I want to link the Match subject to the Math teachers?

Edit: Seed method

protected override void Seed(SchoolContext context)
    {
        GetTeachers().ForEach(t => context.Teachers.Add(t));
        GetSubjects().ForEach(s => context.Subjects.Add(s));
    }

    private static List<Subject> GetSubjects()
    {
        var subjects = new List<Subject> {
            new Subject
            {
                SubjectID = 1,
                SubjectName = "Math"
            },
            new Subject
            {
                SubjectID = 2,
                SubjectName = "Biology"
            },
            new Subject
            {
                SubjectID = 3,
                SubjectName = "English"
            },

        };

        return subjects;
    }

    private static List<Teacher> GetTeachers()
    {
        var teachers = new List<Teacher> {
            new Teacher
            {
                TeacherID = 1,
                TeacherName = "Math Teacher",
                TeacherOffice = "A007",
           },
             new Teacher
            {
                TeacherID = 2,
                TeacherName = "Math Teacher 2",
                TeacherOffice = "A008",
           },
             new Teacher
            {
                TeacherID = 3,
                TeacherName = "Biology Teacher",
                TeacherOffice = "A009",
           },

        };

        return teachers;
    }
Noctix
  • 33
  • 1
  • 6
  • Use one of the entity and feed the collection. EF will handle the whole thing because it knows that manay-to-many exists betweent the two entites. – CodeNotFound Jun 06 '18 at 21:10
  • @CodeNotFound Would you mind giving me an example? Like, I have to do this in the base class or in the DBInitilaizer? Thank you. – Noctix Jun 06 '18 at 21:18
  • Can you show us how your actual Seed method look like so I copy there and extract a sample code for you. – CodeNotFound Jun 06 '18 at 21:19
  • @CodeNotFound Edited my original post to show the Seed method. – Noctix Jun 06 '18 at 21:29

0 Answers0