1

我有两个相关实体,如下所示

public partial class Student{
   public int StudentId{ get; set; }
   public string Name{ get; set; }
   public ICollection<Subject> Subjects{get;set;}
}

public partial class Subject{
   public int SubjectId{ get; set; }
   public int StudentId{ get; set; }
   public string SubjectName{ get; set; }
   public Student Student{ get; set; }
}

在 EF6 中,我可以按如下方式保存这些相关对象并且工作正常。

var student = new Student{
Name = "John Doe"
}

_dbContext.Sudents.Add(student);

var subjects = new List<Subject>{
new Subject{StudentId = student.StudentId, SubjectName = "Math"},
new Subject{StudentId = student.StudentId, SubjectName = "Biology"}
}

_dbContext.Subjects.AddRange(subjects);

_dbContext.SaveChanges();

上述代码在 EF Core 中不起作用,因为 Subject 实体中的 StudentId 始终没有价值。

为了能够保存在 EF Core 我必须如下

var subjects = new List<Subject>{
new Subject{SubjectName = "Math"},
new Subject{SubjectName = "Biology"}
}

var student = new Student{
Name = "John Doe",
Subjects = subjects
}

_dbContext.Sudents.Add(student);

_dbContext.SaveChanges();

EF Core 中发生了哪些更改,因此我必须更改语法才能保存这些相关实体?

提前致谢

4

1 回答 1

0

您无法通过仅将学生添加到上下文中来获取 StudentId。只有在运行 SaveChanges 后才能获取密钥。这就是为什么您的第一个示例无法正常工作的原因。但是,如果您将代码更改为此,它将起作用

var student = new Student{
Name = "John Doe"
}

_dbContext.Sudents.Add(student);
_dbContext.SaveChanges();

var subjects = new List<Subject>{
new Subject{StudentId = student.StudentId, SubjectName = "Math"},
new Subject{StudentId = student.StudentId, SubjectName = "Biology"}
}

_dbContext.Subjects.AddRange(subjects);
_dbContext.SaveChanges();

或者(感谢@SvyatoslavDanyliv 的提示)您可以尝试分配整个学生实例而不是 studentId

var student = new Student{
Name = "John Doe"
}

var subjects = new List<Subject>{
new Subject{Student=student, SubjectName = "Math"},
new Subject{Student = student, SubjectName = "Biology"}
}

_dbContext.Subjects.AddRange(subjects);
_dbContext.SaveChanges();

在这种情况下,您也只能调用 SaveChanges 一次。

于 2021-05-21T20:43:18.553 回答