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,但是调试器没有到达下一行。