【问题标题】:Entity Framework Foreign Key Error with Insert插入的实体框架外键错误
【发布时间】: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


    【解决方案1】:

    通过选择“copiedClass”的学生和教师,您实际上是在选择class_id 为“classId”的班级的学生和教师到数据库上下文中。这些对象保留在内存中。
    接下来,您可能会更改这些对象的 class_id,并将它们插入数据库。一切都很好,直到插入完成并且缓存尝试更新。此缓存具有对所有这些已获取对象的引用,但具有不同的 class_id。
    您使用 ToList 获取的学生现在已链接到另一个班级,这与上下文不一致。

    复制对象时,您有 2 个干净的选项:
    1. 创建新对象,复制先前对象的属性并插入它们

    2. 使用第一个上下文获取对象,使用第二个上下文插入新对象

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-13
      • 2011-12-17
      • 2011-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多