7
votes

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?

1
Sorry to ask but did you try Transaction?Luke Vo
Do you generate primary key values on your own, instead of Identity or GUID?Thangadurai
Yes I do because I get the primary key from another service.Shamshiel

1 Answers

9
votes

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