Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framwork Core – Is a “Insert if not exists” possible?

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?

like image 496
Shamshiel Avatar asked Mar 14 '19 07:03

Shamshiel


1 Answers

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

like image 145
Ryan Sparks Avatar answered Oct 24 '22 09:10

Ryan Sparks