All articles

PostgreSQL and EF Core: DB-first, queries and concurrency

The Npgsql provider, scaffolding, LINQ translation, AsNoTracking, revision checks, Serializable transactions and safe retries.

t.Turgay
PostgreSQL and EF Core: DB-first, queries and concurrency

EF Core manages queries and changes between an object model and a relational database. Npgsql supplies PostgreSQL integration. In a DB-first workflow, SQL schema is the starting point, and query shape, constraints and concurrency are designed alongside it. This guide explains the data and transaction boundaries behind the tooling.

The Npgsql provider and DbContext lifetime

Npgsql.EntityFrameworkCore.PostgreSQL integrates EF Core with PostgreSQL. UseNpgsql configures the provider and connection. A connection pool and a DbContext lifetime are different: a short-lived context does not imply opening a new physical TCP connection for every request.

DbContext is a unit-of-work and change-tracking boundary, not a thread-safe container for parallel queries. Independent concurrent work needs an explicit context and transaction design. A long-running worker should not retain one growing tracked entity set for its entire lifetime.

Npgsql — EF Core provider

DB-first and generated scaffold output

Scaffolding generates entities and a DbContext from an existing database. Numbered SQL scripts make table, constraint and index changes reviewable. Handwritten business behavior inside generated files can disappear on regeneration, so keep it in a durable extension boundary.

This illustrative command expects Name=ConnectionStrings:Main to resolve through design-time configuration. The tooling project must actually supply that configuration. --no-onconfiguring avoids embedding the connection in generated code. Review output locations and selected tables before regenerating.

dotnet ef dbcontext scaffold   Name=ConnectionStrings:Main   Npgsql.EntityFrameworkCore.PostgreSQL   --context DataContext   --context-dir Generated/Context   --output-dir Generated/Models   --no-onconfiguring

Microsoft Learn — reverse engineering

LINQ translation, projection and pagination

Filters, ordering and projections on IQueryable form an expression that the provider can translate. ToListAsync executes and materializes the result. Filtering before that boundary differs from fetching the table and filtering in application memory.

AsNoTracking reduces tracking work for reads, and Select fetches only required fields. Offset pagination needs deterministic ordering; an identifier tie-breaker avoids ambiguity among equal timestamps. Investigate large-offset cost and indexes using actual query plans.

var rows = await db.Entries
    .AsNoTracking()
    .Where(x => x.IsPublished)
    .OrderByDescending(x => x.CreatedAt)
    .ThenBy(x => x.Id)
    .Skip((page - 1) * pageSize)
    .Take(pageSize)
    .Select(x => new { x.Id, x.Title, x.CreatedAt })
    .ToListAsync(ct);

Optimistic concurrency and revision

Optimistic concurrency verifies the previously read version during a write. With revision configured as a concurrency token, EF Core can include the original value in the update predicate. A tracked SaveChanges operation can then raise DbUpdateConcurrencyException when the expected row was not updated.

ExecuteUpdateAsync does not automatically apply that tracked concurrency policy. Include the expected revision in its filter and inspect the affected-row count. A conflict needs a deliberate comparison with current data rather than blindly resubmitting the same stale decision.

Microsoft Learn — concurrency conflicts

Serializable isolation and transaction retries

Serializable requires concurrent effects to remain compatible with some serial execution. PostgreSQL can reject an incompatible transaction with 40001 serialization_failure. A 40P01 deadlock_detected also requires handling at the transaction boundary.

Retrying means rerunning the decision-making reads as well as the final write. Serializable does not promise that every concurrent attempt succeeds. Bound retry count and total duration explicitly rather than turning conflicts into an indefinite loop.

PostgreSQL — transaction isolation

Execution strategies and external side effects

An EF Core execution strategy may rerun its delegate. An explicitly created transaction belongs inside that scope. Confirm which failures the configured Npgsql strategy retries; opening a transaction alone does not enable retry handling.

In this simplified fragment, work rereads its inputs and persists changes through the context. Tracking state is cleared before a new attempt. SMTP sends and Storage writes cannot be undone by PostgreSQL rollback, so external effects need an appropriate persisted-intent boundary outside blindly retryable work.

var strategy = db.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () => {
    db.ChangeTracker.Clear();
    await using var transaction = await db.Database.BeginTransactionAsync(
        IsolationLevel.Serializable, ct);
    await work(db, ct); // re-read, decide, save
    await transaction.CommitAsync(ct);
});

Microsoft Learn — connection resiliency

Related technical articles

You have reached the end of this orbit.
Explore more articles
turgay.A little code, a few pixels, a lot of curiosity.© 2026 · Made on Earth