Upserts in EF Core With PostgreSQL

databasedotnetef-corepostgresql
Upserts in EF Core With PostgreSQL

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.

Two concurrent requests both SELECT the same SKU and find nothing, then both INSERT it; the first insert succeeds and the second fails with a 23505 duplicate key violation

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:

  • EXCLUDED is the row the INSERT tried to write. Referencing it means you write the new values once, in the VALUES clause, 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 WHERE clause 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 UPDATE via ExecuteSqlAsync, with EXCLUDED for the new values.
  • Upserts everywhere: FlexLabs.Upsert for typed, provider-portable statements.
  • Bulk sync jobs: one statement with unnest over arrays, plus an IS DISTINCT FROM guard 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.

  • Using Read Replicas in .NET Applications

    Routing reads to replicas is the standard way to scale a read-heavy database, but replication lag introduces a new class of bugs. Here is how to route queries to replicas in .NET with EF Core, and how to protect read-your-writes consistency while doing it.

  • Full-Text Search in PostgreSQL With EF Core

    You do not need Elasticsearch to add ranked search to your application. PostgreSQL ships tsvector, GIN indexes, and ranking built in, and EF Core maps the whole pipeline to LINQ. Here is how to build ranked full-text search with a generated column and one GIN index.

  • PostgreSQL Indexing for .NET Developers

    B-tree indexes cover most of your queries. Learn when GIN, partial, and covering indexes beat a plain B-tree for the rest, and how to configure each one from EF Core so it survives your migrations.

Browse all Databases guides →
Loading comments...

Whenever you're ready, there are 5 ways I can help you:

  1. Pragmatic Self-Hosting: Learn to deploy and run your apps on a VPS with Dokploy and Tailscale. Keep administration private, automate releases, and practice restoring backups, with source code and a runbook you can reuse.
  2. Pragmatic Clean Architecture: Join 5,000+ students in this comprehensive course that will teach you the system I use to ship production-ready applications using Clean Architecture. Learn how to apply the best practices of modern software architecture.
  3. Modular Monolith Architecture: Join 2,800+ engineers in this in-depth course that will transform the way you build modern systems. You will learn the best practices for applying the Modular Monolith architecture in a real-world scenario.
  4. Pragmatic REST APIs: Join 1,900+ students in this course that will teach you how to build production-ready REST APIs using the latest ASP.NET Core features and best practices. It includes a fully functional UI application that we'll integrate with the REST API.
  5. Patreon Community: Join a community of 5,000+ engineers and software architects. You will also unlock access to the source code I use in my YouTube videos, early access to future videos, and exclusive discounts for my courses.

The .NET Weekly

One practical .NET tip, every Saturday.

Join 66,000+ engineers who read it. Free, and you can unsubscribe any time.