【发布时间】:2015-01-06 23:03:45
【问题描述】:
我们有一个使用 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."
为什么我们只通过定义两个变量就会得到这个错误?我们甚至不在任何其他代码中使用它们。
【问题讨论】:
标签: c# entity-framework foreign-keys foreign-key-relationship