Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DbContext.Entry().Reference().Load() falsely tracks existing reference entity as Added #35762

Open
Ben555555 opened this issue Mar 10, 2025 · 0 comments

Comments

@Ben555555
Copy link

Ben555555 commented 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:

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

Your code

var childResidenceEntity = new
{
MunicipalityId = 1
};

await dbContext.Entry(childResidenceEntity)
    .Reference(childResidence => childResidence.Municipality)
    .LoadAsync(cancellationToken);

await dbContext.SaveChangesAsync(cancellationToken);

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

@Ben555555 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant