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

c# entity-framework entity-framework-core

Question

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
2
3/14/2019 7:49:19 AM

Accepted Answer

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

3
3/14/2019 8:03:19 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