Entity Framework Core: how to map different object instances to the same entity?

c# entity-framework-core

Question

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
    }
}
1
0
2/5/2020 7:29:24 PM

Popular Answer

Simple:

var teacher1 = ...;
var teacher2 = ...;

List<Student> students = new List<Student>()
    {
        new Student(){Name = "Student 1", Teacher = teacher1 },
        new Student(){Name = "Student 2", Teacher = teacher1 },
        new Student(){Name = "Student 3", Teacher = teacher2 },
        new Student(){Name = "Student 4", Teacher = teacher2 },
    };

context.Students.AddRange(teacher1, teacher2);
context.Students.AddRange(students);

context.SaveChanges();

This assumes that the teachers are created elsewhere and saved in the same unit of work as the students.

1
2/5/2020 5:35:45 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow