You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When I execute the following code, there will be an exception when saving the changes, because EF tries to save an entity that already exists:
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): Violation of PRIMARY KEY constraint 'PK_Municipalities'. Cannot insert duplicate key in object 'dbo.Municipalities'. The duplicate key value is (1).
Ben555555
changed the title
DbContext.Entry().Reference().Load() falsely tracks existing referenced entities as Added
DbContext.Entry().Reference().Load() falsely tracks existing reference entity as Added
Mar 10, 2025
Bug description
When I execute the following code, there will be an exception when saving the changes, because EF tries to save an entity that already exists:
Your code
The only workaround is to change the state before saving:
dbContext.Entry(childResidenceEntity.Municipality!).State = EntityState.Unchanged;
Is this behaviour by the design (which I would not understand why)?
Stack traces
Verbose output
EF Core version
8.1.5
Database provider
SqlServer
Target framework
.NE 8
Operating system
Windows 11
IDE
Visual Studio 2022
The text was updated successfully, but these errors were encountered: