Student
和Teacher
是我的关系many-to-many
。
当我在数据库中存在Student
并希望添加新的Teacher
时,我会尝试以下代码。
但是符合要求:
addedTeachers.ForEach(a => dbStudent.Teacher.Add(a));
我收到错误
“an object with the same key already exists in the objectstatemanager. the objectstatemanager cannot track multiple objects with the same key
”。
怎么了?
void Update(Student s)
{
using(var context = new MyEntities(connectionString))
{
context.ContextOptions.LazyLoadingEnabled = false;
var dbStudent = context.Student.Include("Teacher").Where(a => a.Id == s.Id).SingleOrDefault();
var dbTeachers = dbStudent.Teacher.ToList();
var newTeachers = s.Teacher.ToList();
var addedTeachers = newTeachers.Except(dbTeachers).ToList();
var deletedTeachers = dbTeachers.Except(newTeachers).ToList();
addedTeachers.ForEach(a => dbStudent.Teacher.Add(a));
deletedTeachers.ForEach(a => dbStudent.Teacher.Remove(a));
context.SaveChanges();
}
}
修改
其他奇怪的事情:
在此行之前,异常dbStudent.Teacher.Count
为0.但异常为1.当然addedTeachers.Count
也是1,但调试器未到达下一行。
答案 0 :(得分:1)
问题是s
,dbStudent
具有相同的主键。 Teacher
集合中的s.Teacher
个实例可能会引用s
个实例。然后,当您致电addedTeachers.ForEach(a => dbStudent.Teacher.Add(a));
时,EF会识别链接到教师实例的所有对象,并尝试添加它们。
尝试
addedTeachers.ForEach(a => { a.Students.Remove(s);
a.Students.Add(dbStudent);
dbStudent.Teacher.Add(a);});
答案 1 :(得分:0)