Search code examples
.net-coreentity-framework-coredbcontext

The instance of entity type 'VALUE' cannot be tracked because another instance with the same key value for {'OrderId'} is already being tracked


I decided to add models to work with the database.

That's how it was and working

public sealed class DatabaseContext : DbContext
{
   public DbSet<Payment> Payments { get; set; } = null!;

I just added exactly the same model, with the same fields and called it PaymentEntity, now I have an error when working with the database.

public async Task UpdateAsync(PaymentEntity paymentEntity)
{
   databaseContext.Payments.Update(paymentEntity);
   await databaseContext.SaveChangesAsync().ConfigureAwait(false);
}

callback for externalOrderId: '690f11f9713847deab1228c3f76e5994' was received, but some exceptions was thrown System.InvalidOperationException: The instance of entity type 'PaymentEntity' cannot be tracked because another instance with the same key value for {'OrderId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

I did the migration and update of the database. I know about AsNoTracking, ChangeTracker.Clear(), But this seems not the best solution


Solution

  • Avoid using the Update method whenever possible. Instead, modify the entity retrieved from the database.

    public async Task UpdateAsync(PaymentEntity paymentEntity)
    {
        var entity = await databaseContext.Payments.FindAsync(paymentEntity.Id);
        if (entity == null)
            throw new Exception("Entity not found.");
    
        databaseContext.Entry(entity).CurrentValues.SetValues(paymentEntity);
    
        await databaseContext.SaveChangesAsync();
    }