Newton Aigbokhan
Subscribe

EF Core Indexing Strategies Across SQL Server and PostgreSQL

Defining composite, filtered, and covering indexes inside IEntityTypeConfiguration<T>, eliminating slow offset pagination, and avoiding non-sargable LINQ queries.

Most slow Entity Framework Core queries aren’t caused by EF Core itself — they’re caused by schemas designed solely around object relationships rather than actual read and write paths. When a table passes a few million rows, missing composite indexes, offset pagination (Skip().Take()), and non-sargable LINQ expressions quickly turn 12ms endpoints into multi-second table scans.

The cleanest way to keep database performance coupled to your domain model is declaring intentional indexes right inside IEntityTypeConfiguration<T> — and understanding the small differences between SQL Server and PostgreSQL when you generate migrations.

1. Composite Column Order Matches Query Selectivity

Suppose your most frequent dashboard query filters by TenantId and Status, ordered descending by CreatedAtUtc. Putting CreatedAtUtc first in an index forces the engine to scan irrelevant tenants; putting (TenantId, Status, CreatedAtUtc) narrows the B-tree slice immediately:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

public sealed class ViolationRecordConfiguration : IEntityTypeConfiguration<ViolationRecord>
{
    public void Configure(EntityTypeBuilder<ViolationRecord> builder)
    {
        builder.HasKey(x => x.Id);

        // Equality columns first (TenantId, Status), range/sort column last (CreatedAtUtc)
        builder.HasIndex(x => new { x.TenantId, x.Status, x.CreatedAtUtc })
            .HasDatabaseName("IX_ViolationRecords_Tenant_Status_Created")
            .IsDescending(false, false, true);
    }
}

If 90% of queries only target Pending records (Status == ViolationStatus.Pending), you can shrink index size dramatically with a filtered (partial) index:

builder.HasIndex(x => new { x.TenantId, x.CreatedAtUtc })
    .HasDatabaseName("IX_ViolationRecords_Pending_Tenant_Created")
    .HasFilter("\"Status\" = 0"); // Use "[Status] = 0" for SQL Server

Cross-engine note: SQL Server quotes identifiers with brackets ([Status]) while PostgreSQL via Npgsql quotes identifiers with double quotes ("Status"). If a single codebase targets both providers, isolate provider-specific .HasFilter(...) expressions using Database.IsNpgsql() / Database.IsSqlServer() or separate migration assemblies.

2. Eliminate Key Lookups with Covering (INCLUDE) Columns

When a list query selects only 3–4 fields (Id, PlateNumber, Amount), a normal index still forces the engine to hop back to the clustered table/heap for every matched row to read PlateNumber and Amount. Adding non-key INCLUDE columns lets both SQL Server and PostgreSQL satisfy the query purely from the index:

// Supported by both Microsoft.EntityFrameworkCore.SqlServer and Npgsql.EntityFrameworkCore.PostgreSQL
builder.HasIndex(x => new { x.TenantId, x.CreatedAtUtc })
    .HasDatabaseName("IX_ViolationRecords_Tenant_Created_Covering")
    .IncludeProperties(x => new { x.PlateNumber, x.Amount });

Keep IncludeProperties strictly to narrow summary columns — stuffing large nvarchar(max) or jsonb payloads into covering indexes bloats RAM and slows down every INSERT/UPDATE.

3. Replace Offset Pagination with Keyset Pagination

Skip(10_000).Take(50) forces the database to read and discard 10,000 rows on every page turn. Switching to keyset (seek) pagination uses the composite index directly so page 1,000 runs at the same speed as page 1:

public async Task<IReadOnlyList<ViolationSummaryDto>> GetPageAsync(
    Guid tenantId,
    DateTimeOffset? afterCreatedAt,
    Guid? afterId,
    int pageSize,
    CancellationToken ct)
{
    var query = dbContext.ViolationRecords
        .AsNoTracking()
        .Where(v => v.TenantId == tenantId);

    if (afterCreatedAt.HasValue && afterId.HasValue)
    {
        query = query.Where(v =>
            v.CreatedAtUtc < afterCreatedAt.Value ||
            (v.CreatedAtUtc == afterCreatedAt.Value && v.Id.CompareTo(afterId.Value) < 0));
    }

    return await query
        .OrderByDescending(v => v.CreatedAtUtc)
        .ThenByDescending(v => v.Id)
        .Take(pageSize)
        .Select(v => new ViolationSummaryDto(v.Id, v.PlateNumber, v.Amount, v.CreatedAtUtc))
        .ToListAsync(ct);
}

4. Keep LINQ Predicates Sargable

Even a textbook index gets ignored if your LINQ filter wraps the column in a runtime transformation:

  • Avoid: .Where(v => v.PlateNumber.ToUpper() == normalizedPlate) or .Where(v => v.CreatedAtUtc.Date == targetDate) — wrapping the column defeats B-tree seeks.
  • Prefer: Normalize strings (UpperPlate) on write (or configure a case-insensitive collation), and rewrite date equality as an explicit half-open range:
var dayStart = targetDate.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
var dayEnd = dayStart.AddDays(1);

var results = await dbContext.ViolationRecords
    .AsNoTracking()
    .Where(v => v.CreatedAtUtc >= dayStart && v.CreatedAtUtc < dayEnd)
    .ToListAsync(ct);

Whenever you ship a new EF Core migration or alter a query shape, capture the generated SQL via ToQueryString() and run EXPLAIN (ANALYZE, BUFFERS) in PostgreSQL or inspect the actual execution plan in SQL Server. Five minutes checking whether an Index Seek actually happened saves weeks of firefighting once traffic grows.