I’m currently struggling with a simple SQL problem that I don’t seem to be able to fix with “pure” Entity Framework Core 2.2.
How can I check if an entity already exists during the insert without doing the following?
var entity = await _repository.Get(message.Id);
if(entity == null)
{
entity = new Entity ();
// do something with the entity
await _repository.AddAsync(entity);
}
else
{
// do something with the entity
await _repository.Update(entity);
}
await _repository.SaveChangesAsync();
This is not safe enough. I'm constantly getting primary key violations. My service runs on multiple instances and I get messages within a short period of time that have the same primary key.
Is there a better and safer way to check if an entity already exists in Entity Framework Core without writing the SQL myself?