[英]How to insert multiple entities that have same value for navigation property?
I have POCO like these: 我有这样的POCO:
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public Level Level { get; set; }
}
public class Level
{
public int LevelId { get; set; }
public string Name { get; set; }
public ICollection<Student> Students { get; set; }
}
And here is how I'm saving all students in a single level: 这是我将所有学生保存在一个级别中的方法:
public void InsertAllFirstLevelStudents(List<Student> students)
{
// Here all students belong to the same level
var level = Utils.GetFirstLevel();
students.ForEach(s => s.Level = level);
context.Students.AddRange(students);
context.SaveChanges();
}
But when saving, I get this error: 但是在保存时,出现此错误:
entity object cannot be referenced by multiple instances of IEntityChangeTracker 实体对象不能由IEntityChangeTracker的多个实例引用
When I fetch the same level individually like: context.Levels.FirstOrDefault(l=> l.Name == "First"); 当我分别获取相同的级别时: context.Levels.FirstOrDefault(l => l.Name ==“ First”); , there is no problem, but of course, it then executes separate db queries to which is what I'm trying to avoid. ,没有问题,但是,当然,它然后执行单独的数据库查询,这是我要避免的查询。
What can be done for this ? 为此可以做什么?
public class Student
{
public int StudentId { get; set; }
public LevelId {get; set;}
public string Name { get; set; }
[ForeignKey("LevelId")]
public Level Level { get; set; }
}
and then 接着
students.ForEach(s => s.LevelId = level.LevelId);
You can just add the student to the Students
collection of the level. 您可以将学生添加到级别的“ Students
集合中。
// Here all students belong to the same level
var level = Utils.GetFirstLevel();
foreach (var student in students) {
level.Students.Add(student);
}
context.Students.AddRange(students); // Probably not necessary
context.SaveChanges();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.