How could I map different object instances of an entity to the same row into a datatable using Entity Framework Core?
In another word, how does Entity Framework Core compare entities which are not yet inserted into a database (otherwise I guess it only has to compare the primary key) and figures out that two objects should be mapped to a single entity? Does it compare instance references? Or call the default Equality operator?
Summarizing my problem, let's imagine I have a school containing students and teacher, and that I want one data row to be created for each teacher name but I cannot reuse the same teacher instance, how could I tell EF to do that?
public class Student
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public Teacher Teacher { get; set; }
}
public class Teacher
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class SchoolContext : DbContext
{
public DbSet<Teacher> Teachers { get; set; }
public DbSet<Student> Students { get; set; }
}
public class SchoolGenerator
{
public static void CreateASchool(SchoolContext context)
{
List<Student> students = new List<Student>()
{
new Student(){Name = "Student 1", Teacher = new Teacher(){Name = "Teacher 1"}},
new Student(){Name = "Student 2", Teacher = new Teacher(){Name = "Teacher 1"}}, // I cannot re-use the previous instance of Teacher 1 for this student
new Student(){Name = "Student 3", Teacher = new Teacher(){Name = "Teacher 2"}},
new Student(){Name = "Student 4", Teacher = new Teacher(){Name = "Teacher 2"}},
};
context.Students.AddRange(students);
context.SaveChanges(); // I want to create only TWO teacher rows, one by name, and FOUR student rows
}
}