Insert/Delete/Insert results in tracking error

c# entity-framework-core


I have a console .NET Core 2.1 app that is using EF Core 2.1. It talks to a Database to read and insert rows. This database is also being updated by other applications at the same time.

The issues I run into is, I create a row from my console app, then an external app deletes this row, and then when I again try to insert the row with the same primary keys, I run into the exception below -

The instance of entity type 'XYZ' cannot be tracked because another instance with the key value '{ID: 11, ABC: 136, DEF: 97}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

Below is my code

var entity = PopulateValuesFor(XYZ);

var existingXYZ = _Context.TABLE1
            .Include(r => r.TABLE2)
            .Include(r => r.TABLE3)
            .FirstOrDefault(r => r.Id == 1234);                                 

        if (existingXYZ == null)

The flow is

  1. Above code is called --> row is instered
  2. External app deletes the row from data
  3. Above code is called again --> exception

How do I tell the DbContext that the entity is no longer in the database... flush out your entries and add this row to the database again? Because it's a console app, only 1 instance of DbContext is being used, which get's injected into the class implementing this method.

9/19/2018 9:16:53 PM

Accepted Answer

You seem to have a long lived static context. I would suggest wrapping the above in a using statement and going for a short lived context. That way your context wont think its inserted entity already.

9/19/2018 9:05:38 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow