c# - Entity Framework: Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value -
i found multiple posts issue, issue little different , error shown matches scenario.
i have 2 different schema under database. e.g.
preschool.students
&school.students
. , per our requirements, rest same bothstudents
tables, including primary key.now in code, updating record of 'preschool.students' using following code:
var wouldbeupdatedstudent = await context.students .findasync(student.studentidentity).configureawait(false); wouldbeupdatedstudent = student; //updated student object context.entry(wouldbeupdatedstudent).state = entitystate.modified; // line throws error var result = await context.savechangesasync().configureawait(false);
under
onmodelcreating
settablename
&schemaname
each of entity. this, expecting whenever change entity/ model state, should catch correct table per setting done underonmodelcreating
. not happening , throws exception.
i tried using
context.students.asnotracking()
works if no cascading students entity. however, there cascading/children entities same ddl. e.g.context.student.exams
logically didn't answer gives proper explanation -fix on error. this answer resolved issue. 1 more think observed solution is, if new object has same values per entity underlying database, won't update table.
e.g.
context.set<student>().addorupdate(wouldbeupdatedstudent); result = await context.savechangesasync().configureawait(false);
reason cannot use
asnotracking()
because have nested entities same across other schema. if useasnotracking()
@ top level entity, same error child level. same mentioned in question.
Comments
Post a Comment