Entity Framework: The binding of an object of type "MODELNAME" failed because another object of the same type already has the same primary key value

I found a few posts for this problem, however my problem is slightly different, and the error shown matches my scenario.

  • I have two different schemas in the database. e.g. PreSchool.Students and School.Students . And in accordance with our requirements, the rest is the same for both Students tables, including the primary key.

  • Now in my code, I am updating the "PreSchool.Students" entry using the following code:

     var wouldBeUpdatedStudent = await context.Students .FindAsync(student.StudentIdentity).ConfigureAwait(false); wouldBeUpdatedStudent = student; //updated student object context.Entry(wouldBeUpdatedStudent).State = EntityState.Modified; // This line throws error var result = await context.SaveChangesAsync().ConfigureAwait(false); 
  • In OnModelCreating I clearly set tableName and SchemaName for each of Entity. Thus, I expect that whenever I change the state of an object / model, it should catch the correct table according to the setting made in OnModelCreating . However, this does not occur and throws an exception.

I tried using context.Students.AsNoTracking() , this works if you do not cascade on students' Entity. However, there are some cascading / child objects that are also the same DDL. e.g. context.Student.Exams

0
c # sql-server entity-framework
Aug 14 '17 at 19:16
source share
1 answer

Logically, I did not get an answer that gives the correct explanation of -fix for this error. However, this answer resolved my issue. Another thought I observed is that the solution is that if the new object has exactly the same values ​​as for the entity-based database, it will not update the table.

eg.

 context.Set<Student>().AddOrUpdate(wouldBeUpdatedStudent); result = await context.SaveChangesAsync().ConfigureAwait(false); 

Reason I cannot use AsNoTracking() , because I have nested objects that are the same for another circuit. So even if I use AsNoTracking() in a top-level entity, I get the same error for the child level. Same as in my question.

0
Aug 15 '17 at 16:32
source share



All Articles