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?
Currently Upsert is not natively supported in EF Core (open GitHub issue here: https://github.com/aspnet/EntityFrameworkCore/issues/4526#issuecomment-366818031)
Open source library that extends EF Core to support this can be found here: https://github.com/artiomchi/FlexLabs.Upsert
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With