我有两个相关实体,如下所示
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 中发生了哪些更改,因此我必须更改语法才能保存这些相关实体?
提前致谢