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.

  1. i have 2 different schema under database. e.g. preschool.students & school.students. , per our requirements, rest same both students tables, including primary key.

  2. 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); 
  3. under onmodelcreating set tablename & schemaname each of entity. this, expecting whenever change entity/ model state, should catch correct table per setting done under onmodelcreating. 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 use asnotracking() @ top level entity, same error child level. same mentioned in question.


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -