Unable to re-insert after unique key violation

ef-core-2.1 entity-framework-core

Question

I have the following scenario:

A business logic function that uses EF Core2 checks if a record already exists. If the record does not exists, it is inserted on the database.

I have multiple threads calling this business logic function. What happens is:

If the function is called simultaneous with the same parameters, both instances checks if the record exists - and it does not exists. So both instances inserts the same record.

When context.SaveChanges() is called on the first instance, all goes ok. But the second SaveChanges() throws an exception because the record already exists (there is an unique index on the database).

If i catch that exception and try to insert with new value for UNIQUE_KEY, still it's throwing an exception since previously added entity still in track.

How can I implement this to avoid the exception?

1
1
6/11/2019 9:17:31 AM

Popular Answer

Instead of simply adding a new entity inside your catch-block, you could modify the existing entity that caused the exception.

foreach (var entry in _dbContext.ChangeTracker.Entries<YourEntity>().Where(e => e.State == EntityState.Added)))
{
    entry.Entity.YourProperty = newvalue;
}

Just iterate through all your entities of given type and update your property that has a unique constraint.

0
6/17/2019 9:31:41 AM


Related Questions





Related

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