簡體   English   中英

Entity Framework Core:如何將不同的對象實例映射到同一個實體?

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

如何使用 Entity Framework Core 將實體的不同對象實例映射到同一行到數據表中?

換句話說,Entity Framework Core 如何比較尚未插入數據庫的實體(否則我猜它只需要比較主鍵)並確定兩個對象應該映射到單個實體? 它是否比較實例引用? 或者調用默認的 Equality 運算符?

總結我的問題,讓我們假設我有一所包含學生和老師的學校,並且我希望為每個老師姓名創建一個數據行,但我不能重用同一個老師實例,我怎么能告訴 EF 這樣做呢?

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
    }
}

簡單的:

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();

這假設教師是在別處創建的,並與學生保存在同一工作單元中。

為什么要手動編碼 DbContext? 請改用 Scaffold-DbContext。

1) 通過在 SQL Server 中添加新的“TeacherID”列來重新設計您的 Student 表

2)在SQL Server中創建Student表和Teacher表的關系

3) 運行 Scaffold-DbContext 來更新 DbContext 和實體

4)使用下面的代碼

var teacher1 = new Teacher(){ Name = "Teacher 1" };
var teacher2 = new Teacher(){ Name = "Teacher 2" };

context.Teachers.AddRange(teacher1, teacher2);

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

context.Students.AddRange(students);
context.SaveChanges();

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM