Every codebase has this method somewhere:
var existing = await dbContext.Products
.SingleOrDefaultAsync(p => p.Sku == sku);
if (existing is null)
{
dbContext.Products.Add(new Product { Sku = sku, Price = price });
}
else
{
existing.Price = price;
}
await dbContext.SaveChangesAsync();
It works in development and passes every test.
Under production traffic, two requests for the same new SKU run concurrently, both find nothing, both insert, and one fails with 23505: duplicate key value violates unique constraint.
The check and the write are two separate statements, and another request can insert the same SKU between them.
PostgreSQL closes that gap with one atomic statement: INSERT ... ON CONFLICT DO UPDATE.
Below are three ways to run it from EF Core: raw SQL, FlexLabs.Upsert, and bulk upserts with unnest.
Why the Race Exists (and Why Catching the Exception Is a Band-Aid)
Under the default read committed isolation level, each statement sees a snapshot from the moment it starts.
Request A's SELECT and request B's SELECT both run before either INSERT, so both see an empty result.
The database is doing exactly what it promised; I walk through these guarantees in transaction isolation levels for .NET developers.
The common patch is catch-and-retry:
try
{
await dbContext.SaveChangesAsync();
}
catch (DbUpdateException ex)
when ((ex.InnerException as PostgresException)?.SqlState == "23505")
{
// Reload and update instead...
}
It's better than crashing, but now you have two round trips on the conflict path, change-tracker cleanup, and code that's hard to reason about.
The atomic statement is simpler and closes the race in one round trip.
It does write a new row version even when nothing changed, which EF's change tracker would have skipped, unless you add the IS DISTINCT FROM guard shown below.
ON CONFLICT DO UPDATE: The Atomic Upsert
You need a unique index or constraint on the conflict columns. PostgreSQL uses it to detect the collision, so this is not optional:
modelBuilder.Entity<Product>(builder =>
{
builder.HasIndex(p => p.Sku).IsUnique();
});
The SQL in this article assumes Product maps to a products table with snake_case columns (sku, price, updated_at), for example through UseSnakeCaseNamingConvention() from the EFCore.NamingConventions package.
The statement itself:
INSERT INTO products (sku, price, updated_at)
VALUES ('ABC-123', 19.99, now())
ON CONFLICT (sku)
DO UPDATE SET
price = EXCLUDED.price,
updated_at = EXCLUDED.updated_at;
Two details in that statement:
EXCLUDEDis the row theINSERTtried to write. Referencing it means you write the new values once, in theVALUESclause, instead of repeating them.- The whole thing is atomic. Concurrent upserts for the same key serialize inside the database; one inserts, the other updates.
You can also make the update conditional, which avoids pointless writes (and pointless trigger firings):
ON CONFLICT (sku)
DO UPDATE SET price = EXCLUDED.price, updated_at = now()
WHERE products.price IS DISTINCT FROM EXCLUDED.price;
And ON CONFLICT DO NOTHING is the idempotent-insert variant, which is exactly what you want for deduplication tables like the one behind the idempotent consumer pattern.
Option 1: Raw SQL From EF Core
For a single-row upsert, ExecuteSqlAsync with an interpolated string is the shortest safe path.
EF Core turns the interpolation holes into parameters, so there's no injection risk:
public async Task UpsertProductAsync(string sku, decimal price, CancellationToken ct)
{
await dbContext.Database.ExecuteSqlAsync(
$"""
INSERT INTO products (sku, price, updated_at)
VALUES ({sku}, {price}, now())
ON CONFLICT (sku)
DO UPDATE SET
price = EXCLUDED.price,
updated_at = EXCLUDED.updated_at;
""",
ct);
}
To get the resulting row back, add RETURNING and query through the entity.
EF Core can't compose SQL on top of an INSERT, so SingleAsync directly on the query throws; switch to AsAsyncEnumerable() and take the row on the client:
var product = await dbContext.Products
.FromSql(
$"""
INSERT INTO products (sku, price, updated_at)
VALUES ({sku}, {price}, now())
ON CONFLICT (sku)
DO UPDATE SET price = EXCLUDED.price, updated_at = EXCLUDED.updated_at
RETURNING *
""")
.AsNoTracking()
.AsAsyncEnumerable()
.SingleAsync(ct);
(Adding (xmax = 0) to the RETURNING list tells you whether the row was freshly inserted.
The entity query above ignores columns it doesn't map, so read that flag with Database.SqlQuery<bool> or Dapper.)
The trade-offs of raw SQL are the usual ones: column names are hard-coded strings, and refactoring won't catch them. I consider that acceptable for a handful of hot-path upserts, and the broader guidance from EF Core raw SQL queries applies here.
Option 2: FlexLabs.Upsert
If upserts appear all over your codebase, a library keeps them strongly typed:
dotnet add package FlexLabs.EntityFrameworkCore.Upsert
await dbContext.Products
.Upsert(new Product { Sku = sku, Price = price, UpdatedAt = DateTime.UtcNow })
.On(p => p.Sku)
.WhenMatched((existing, incoming) => new Product
{
Price = incoming.Price,
UpdatedAt = incoming.UpdatedAt
})
.RunAsync(ct);
This generates the same ON CONFLICT DO UPDATE under the hood, works across providers (it emits MERGE on SQL Server), and supports collections via UpsertRange.
It is a good fit once a project has more than two or three upsert sites.
EFCore.BulkExtensions covers the same ground with BulkInsertOrUpdateAsync, oriented at very large batches.
Check the current licensing terms before adopting it; it moved away from a pure open-source license a while back.
Option 3: Bulk Upserts With unnest
For synchronization jobs (nightly price feeds, catalog imports), row-at-a-time upserts are too slow.
The Postgres idiom is to pass arrays and unnest them into a single statement:
public async Task UpsertProductsAsync(IReadOnlyList<Product> products, CancellationToken ct)
{
var skus = products.Select(p => p.Sku).ToArray();
var prices = products.Select(p => p.Price).ToArray();
await dbContext.Database.ExecuteSqlAsync(
$"""
INSERT INTO products (sku, price, updated_at)
SELECT sku, price, now()
FROM unnest({skus}, {prices}) AS t(sku, price)
ON CONFLICT (sku)
DO UPDATE SET
price = EXCLUDED.price,
updated_at = EXCLUDED.updated_at;
""",
ct);
}
One statement with two array parameters upserts the whole batch in a single round trip. Npgsql maps the C# arrays to Postgres arrays natively, which most databases don't support. I covered the raw ingestion side in fast SQL bulk inserts with C# and EF Core.
Deduplicate the batch by SKU before sending it.
If the same key appears twice, PostgreSQL rejects the whole statement with ON CONFLICT DO UPDATE command cannot affect row a second time.
One caveat at scale: each upserted row is a write even when nothing changed, unless you add the WHERE ... IS DISTINCT FROM guard.
For feeds where 95% of rows are unchanged, that guard cuts dead tuples and WAL volume by skipping the unchanged rows.
What About MERGE?
PostgreSQL 15 added standard SQL MERGE, and Postgres 17 extended it with RETURNING support.
It's more expressive than ON CONFLICT (it can delete, and it can match on arbitrary conditions), but MERGE is not concurrency-safe the way ON CONFLICT is.
Under concurrent inserts of the same key, MERGE can still raise unique violations, because it doesn't take the same speculative-insertion path.
A practical rule: ON CONFLICT for upserts, MERGE only for batch reconciliation jobs where you control concurrency.
Concurrency Edge Cases
A few edges that show up in production:
- Last write wins. Concurrent upserts for the same key serialize, and the later one overwrites. If you need "only update if newer", encode it:
DO UPDATE SET ... WHERE EXCLUDED.updated_at > products.updated_at. This is the same lost-update reasoning as optimistic locking, pushed into the statement. - The change tracker doesn't know. Raw upserts bypass EF's tracking, so a tracked instance of the same row is now stale. Keep upsert paths and rich-entity paths separate, or clear/reload after bulk operations.
- Partial unique indexes work as conflict targets with the
WHEREclause repeated:ON CONFLICT (email) WHERE deleted_at IS NULL DO UPDATE .... Pair this with the patterns from PostgreSQL indexing for .NET developers.
Summary
The SELECT-then-branch upsert is a race condition. It throws duplicate key exceptions under concurrent load, where they're hardest to debug.
Which one to use:
- One or two upsert sites: raw
ON CONFLICT DO UPDATEviaExecuteSqlAsync, withEXCLUDEDfor the new values. - Upserts everywhere: FlexLabs.Upsert for typed, provider-portable statements.
- Bulk sync jobs: one statement with
unnestover arrays, plus anIS DISTINCT FROMguard to skip no-op writes. - Idempotent inserts:
ON CONFLICT DO NOTHING.
All of them require the unique index that defines what "conflict" means, so create that first.
Frequently Asked Questions
Does EF Core have a built-in upsert method?
No. EF Core decides between INSERT and UPDATE based on change-tracker state, not database state. For a true atomic upsert you use raw SQL with ON CONFLICT, or a community library like FlexLabs.Upsert that generates it for you.
Why is SELECT then INSERT or UPDATE not safe?
Two concurrent requests can both find no existing row, and both try to INSERT. One succeeds and the other throws a unique constraint violation. The check and the write are separate statements, so there is a race window between them.
What does ON CONFLICT DO UPDATE require?
The conflict target must be a column set backed by a unique index or unique constraint. PostgreSQL uses that index to detect the conflict, so an upsert on a non-unique column combination is not possible.
What is the EXCLUDED table in a PostgreSQL upsert?
EXCLUDED is a pseudo-row holding the values that the failed INSERT attempted to write. In the DO UPDATE clause you use it to apply the new values, for example SET price = EXCLUDED.price.
How do I upsert many rows at once in EF Core?
Send one INSERT with multiple value rows and an ON CONFLICT clause, use unnest with arrays for large batches, or use a library like FlexLabs.Upsert or EFCore.BulkExtensions that batches upserts for you.

