0

Some of my entities have navigation properties as they have a foreign key to another entity in the database. In my code, I've set the primary keys of the navigation properties to link the entities with each other.

The problem is that entity framework sees this as a new entity and tries to add it to the database with next error as a result:

Cannot insert explicit value for identity column in table 'xxx' when IDENTITY_INSERT is set to OFF.

Obviously, because the entity is new and not acquired from the database.

Is there a way in EF to remove the tracking of the entity?

Wouter
  • 154
  • 17
  • Post your code. `Update` will attach a detached entity and *all* related entities in the `Added` state, if their PKs have default values. It can't know that you don't want to save some of them in this particular case. For this error though, it seems that the root entity has a default PK (eg ID=0) but the related entities don't. ` I've set the primary keys of the navigation properties` how was this done? By setting a value to eg `CustomerID` ? Or creating a new `Customer` with a specific `ID`? – Panagiotis Kanavos Jan 18 '23 at 17:13
  • Have a look at the answer I provided to this question: https://stackoverflow.com/questions/75136653/why-do-i-get-tracking-error-while-updating-entity-in-ef-core/75140295#75140295 The issue with references is that you need to take special care when passing entities with references into the scope of a DbContext that wasn't responsible for reading them all. – Steve Py Jan 18 '23 at 21:17
  • @PanagiotisKanavos The the latter case, A new Customer is created with a specific ID. – Wouter Jan 19 '23 at 08:13
  • @StevePy Thank you for your answer. Unfortunately, the method that saves the entity is in an abstract repo. The logic that maps our dto to the entity does not have the context available. We've solved the problem by no longer creating the Customer entity, but by working with ids (FKs), both in our entitiy and in our dto and add [JsonIgnore] to them. – Wouter Jan 19 '23 at 08:13
  • Post your code. Don't make people guess. If you have a `dbContext.Added(model)` call, both `model` and `model.Custoner` are assumed to be *new* entities. If you use `dbContext.Update(model)` and `model.Id` is db-generated, EF will see that `model.ID` is missing and *insert* `model`. It will see that `model.Customer` has an `ID` and treat it as modified. – Panagiotis Kanavos Jan 19 '23 at 08:16

0 Answers0