2

Entity FrameWork를 사용하는 MVC 프로젝트가 있습니다.이 테이블에는 3 개의 테이블, 클래스 테이블, 학생 테이블 및 교사 테이블이 있습니다. 교사 및 학생 테이블은 CLASS_ID별로 클래스 테이블과 관계가 있습니다. 우리는 수업의 사본을 만들어 교사와 학생들과 함께 데이터베이스에 삽입하려고합니다. 우리가 문제가있는 줄을 생략하면 Entity Framework 외부 키 삽입 오류

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." 

말을 런타임 예외가? 다른 코드에서는 사용하지 않습니다.

답변

3

'copiedClass'의 학생과 교사를 선택하면 실제로 class_id 'classId'가 포함 된 클래스의 학생 및 교사를 데이터베이스 컨텍스트로 선택합니다. 이러한 객체는 메모리에 남아 있습니다.
다음으로는 해당 객체의 class_id를 변경하고 데이터베이스에 삽입하는 것이 좋습니다. 삽입이 완료되고 캐시가 업데이트를 시도 할 때까지는 모두 정상입니다. 이 캐시는 가져온 모든 오브젝트에 대한 참조를 갖지만 class_id가 다릅니다.
ToList로 가져온 학생이 이제 다른 클래스에 연결되어 있는데 이는 상황과 일치하지 않습니다.

객체를 복사 할 때, 당신은이 깨끗한 옵션이 있습니다,
1. 새로 만든 객체를 이전 객체의 속성을 복사하여 삽입
또는
2. 개체를 가져 최초의 문맥, 그리고 2 새 개체를 삽입하는 컨텍스트

관련 문제