我们有一个使用Entity FrameWork的MVC项目,其中有三个表,一个类表,一个学生表和一个教师表。教师和学生表通过CLASS_ID与班级表有关系。我们正在尝试制作一个课程的副本,并将其连同其老师和学生一起插入数据库。
public void MakeClassCopy(int classID){
var copiedClass = database.TABLE_CLASS.Where(x => x.ID == classID).First();
var students = copiedClass.TABLE_STUDENTS.ToList(); //Lines that cause the exception
var teachers = copiedClass.TABLE_TEACHERS.ToList(); //Lines that cause the exception
database.TABLE_CLASS.Add(copiedClass);
database.SaveChanges();
string newTableID = copiedClass.ID;
//Insert students and teachers with new CLASS_ID here
}
如果我们省略有问题的行,则此方法有效,但是当像这样执行时,我们会收到一个运行时异常提示
"The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: A referential integrity constraint violation occurred: The property value(s) of 'TABLE_CLASS.ID' on one end of a relationship do not match the property value(s) of 'TABLE_STUDENTS.CLASS_ID' on the other end."
为什么仅通过定义两个变量才能得到此错误?我们甚至不在其他任何代码中使用它们。
通过选择“ copiedClass”的学生和老师,您实际上是在将class_id为“ classId”的班级的学生选择到数据库上下文中。这些对象保留在内存中。
接下来,您可能会更改这些对象的class_id,并将它们插入数据库中。在插入操作完成并且缓存尝试更新之前,一切都很好。该缓存引用了所有这些获取的对象,但是具有不同的class_id。
现在,您使用ToList获取的学生已链接到另一个班级,并且与上下文不一致。
复制对象时,有2个干净的选项:
1.创建新对象,复制先前对象的属性并插入它们,
或者
2.使用第一个上下文获取对象,并使用第二个上下文插入新对象
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句