© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
3 replies
Hulkstance

❔ EF Core "upsert" - insert if it doesn't exist, update if it does

I'm trying to "optimize" the command below.

The term upsert is a combination of the words “update” and “insert.” In the context of relational databases, an upsert is a database operation that will update an existing row if a specified value already exists in a table, and insert a new row if the specified value doesn't already exist.

There are only two tables (the database structure can be find below), and there are different event types for which we have these three booleans. Administrators can change these global notification settings on demand. If the record for a specific event type id doesn't exist, it should load it at runtime. Since these settings can be updated concurrently by many administrators at the same time, I think I should handle DbUpdateConcurrencyException https://github.com/petercwq/EFCorePractice/blob/master/EFCorePractice/DbContextConcurrencyExtension.cs. What do you think?

I'm not so good at EF Core, so I would like to know your opinion. I also had a look at https://stackoverflow.com/questions/5557829/update-row-if-it-exists-else-insert-logic-with-entity-framework and I feel like instead of using a stored procedure or an atomic transaction, I could use Update which cuts off the round trips to the database? I mean I wouldn't need to do .FindAsync and then insert/update.
Stack Overflow
Update Row if it Exists Else Insert Logic with Entity Framework
What is the most efficient way to implement update row if it exists, else insert new row logic using Entity Framework? Or are there any patterns for this?
Update Row if it Exists Else Insert Logic with Entity Framework
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources
Was this page helpful?

Similar Threads

Recent Announcements

Similar Threads

UniqueIdentifer Type does not exist Ef Core
C#CC# / help
2y ago
✅ EF Core doesn't stop tracking list items.
C#CC# / help
15mo ago
✅ Docker + Blazor + EF Core 7 + SQLite = __EFMigrationsHistory doesnt exist
C#CC# / help
3y ago
✅ In Ef Core I can't update-database
C#CC# / help
6mo ago