The standard advice in .NET is to use EF Core for writes and Dapper for the queries that need to be fast. I've repeated that advice myself. Then I built EstimateFlow, a lead-capture app for contractors. It runs on PostgreSQL through Npgsql and EF Core 10. It has ten tables of its own, seventeen migrations and a dashboard full of aggregates.

Dapper has never been added to it. I searched the whole Git history to be sure, and the word doesn't appear in a single commit.

The project still has raw SQL in three places. I also know which queries would make me add a second data access library, and none of them has come up yet.

Reads: projections, not entities

Most of the speed gap between EF and Dapper comes from two defaults. EF loads whole entities, and it tracks them. If you turn both off, there isn't much of a gap left to close.

Nearly every read in the project starts with AsNoTracking() and ends in a Select. This one fills the page that lists a contractor's estimators:

var widgets = await _context.Widgets
    .OwnedBy(userId)
    .OrderByDescending(w => w.Created)
    .Select(w => new WidgetWithLeadsDto
    {
        Id = w.Id,
        Name = w.Name,
        // ...
        LeadCount = w.EstimateRequests.Count(lead => !lead.IsTest),
        NewLeadCount = w.EstimateRequests.Count(lead => !lead.IsTest && lead.Status == EstimateRequestStatus.New),
        // Correlated rather than a second round trip: the estimators
        // page shows install state for every row, and fetching it per
        // widget would be one query per estimator in the list.
        Install = _context.WidgetInstalls
            .Where(i => i.WidgetId == w.Id)
            .Select(i => new WidgetInstallDto
            {
                Hostname = i.Hostname,
                FirstSeen = i.FirstSeen,
                LastSeen = i.LastSeen,
            })
            .FirstOrDefault()
    })
    .ToListAsync(cancellationToken);

That whole thing is one SQL statement. The counts and the install lookup become correlated subqueries, so the page costs one round trip however many estimators there are.

This query used to begin with .Include(w => w.EstimateRequests). It did nothing. When you project with Select, EF works out the joins from the projection and ignores Include entirely. I only removed it while tidying up something else, and I suspect a lot of codebases carry the same dead line.

The dashboard, where Dapper would normally go

The dashboard shows a funnel, a pipeline by status, a win rate, median estimates and a daily series. This is exactly the kind of screen people write Dapper for.

I didn't write a GROUP BY at all. The handler runs a few narrow queries and does the arithmetic in C#:

// Same bound as the per-estimator analytics: retention and the public
// rate limit keep a 90-day window of every estimator small enough to
// group in memory.
var events = await context.WidgetEvents
    .AsNoTracking()
    .Where(e => widgetIds.Contains(e.WidgetId) && !e.IsTest && e.OccurredAt >= eventsSince)
    .Select(e => new { e.WidgetId, e.SessionId, e.Kind, e.StepKey, e.OccurredAt })
    .ToListAsync(cancellationToken);

Each row is five small columns. From there the funnel, the medians and the rest are LINQ over a list in memory.

This is a deliberate shortcut, and the comment says what makes it safe. Events are deleted after ninety days, and the public endpoint that records them is rate limited, so the number of rows has a ceiling. The note I left in the task record is blunter: fine at this scale, revisit if a single estimator passes tens of thousands of sessions a month.

It's also the first place Dapper would go. A median over a window is one line of PostgreSQL and a miserable thing to express in LINQ. If that ceiling ever gets close, I'll write the SQL.

Bulk writes no longer need it

The other classic reason to reach for Dapper was set-based writes. EF used to make you load a thousand rows in order to delete them. Since EF Core 7 it doesn't. This is the job that removes expired leads:

// One unit, retried as a whole: the retrying strategy refuses a
// transaction it did not start itself.
var strategy = context.Database.CreateExecutionStrategy();
var deleted = await strategy.ExecuteAsync(async () =>
{
    await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken);

    await context.EmailSuppressions
        .Where(suppression => suppression.EstimateRequestId != null
            && expired.Contains(suppression.EstimateRequestId.Value))
        .ExecuteUpdateAsync(
            setters => setters.SetProperty(suppression => suppression.EstimateRequestId, (Guid?)null),
            cancellationToken);

    // Messages and notifications go with the lead through ON DELETE CASCADE.
    var count = await context.EstimateRequests
        .Where(lead => expired.Contains(lead.Id))
        .ExecuteDeleteAsync(cancellationToken);

    await transaction.CommitAsync(cancellationToken);
    return count;
});

ExecuteUpdateAsync and ExecuteDeleteAsync each send a single statement and load nothing. The wrapper around them is the part that caught me out. With connection retries enabled, EF refuses to run a transaction you opened yourself, because it can't safely replay half of one. You have to hand the whole unit to the execution strategy so that it can retry all of it.

Where raw SQL did show up

There are three places, and none of them is a hot query.

The first is inside a migration. Lead answers are stored as jsonb, and at one point their shape changed. EF can't express that, so the migration does it with PostgreSQL's JSON operators:

migrationBuilder.Sql(
    """
    UPDATE "EstimateRequests"
    SET "IntakeAnswers" = jsonb_build_object(
        'values', (("IntakeAnswers" - 'specialConditions')::jsonb),
        'selections', jsonb_build_object(
            'specialConditions',
            COALESCE("IntakeAnswers" -> 'specialConditions', '[]'::jsonb))
    )
    WHERE "IntakeAnswers" IS NOT NULL
      AND "IntakeAnswers" ? 'customerType';
    """);

The second went the other way. A later change to pricing settings also needed existing JSON rewritten, and that time I chose not to do it in SQL. The mapping from the old shape to the new one already existed in C#, with tests. Writing it a second time in JSON functions would have given me two versions of one rule and tests for only one of them. So SQL only narrows down the rows, and the code decides what to do with each:

// The column is jsonb, so the candidates are found by a text match
// and decided in code; the match only narrows the rows loaded.
var candidates = await context.Widgets
    .FromSqlRaw(
        """
        SELECT * FROM "Widgets"
        WHERE "Settings" IS NOT NULL
          AND ("Settings"::text ILIKE '%PerSquareFoot%'
            OR "Settings"::text ILIKE '%materialRates%'
            OR "Settings"::text ILIKE '%conditionAdjustments%'
            OR "Settings"::text ILIKE '%minimumProjectPrice%')
        """)
    .ToListAsync(cancellationToken);

var migrated = 0;
foreach (var widget in candidates)
{
    var collapsed = LegacyFlooringPricing.Collapse(widget.Settings);
    if (collapsed is null)
        continue;

    widget.UpdateSettingsJson(collapsed);
    migrated++;
}

if (migrated > 0)
    await context.SaveChangesAsync(cancellationToken);

On my development database it found one candidate row and rewrote it. On the next start it found none.

The third is a one-off that adopts databases created before the project used migrations at all.

All three go through EF: migrationBuilder.Sql, FromSqlRaw and ExecuteSqlRawAsync. I never needed a second library to run a SQL string.

What EF cost me

The inbox query makes four round trips per request: a count of new leads, the list of trades for the filter, the total for paging, and the page itself. Dapper's QueryMultiple would do that in one. I haven't measured it as a problem, so it has stayed as it is.

The search box uses ToLower().Contains(...) where PostgreSQL's ILIKE would be the natural choice. The application layer references only the base EF Core package, and EF.Functions.ILike lives in the Npgsql one. Using it would have pulled the database provider into the layer that's meant not to know which database it's talking to. Npgsql translates my version to lower() and LIKE, which is good enough.

And one bug only showed up because a test ran against the real provider. The dashboard computes "start of day" in the contractor's time zone. I was sending local midnight to the database as a DateTimeOffset with a non-zero offset, and Npgsql only writes values whose offset is zero. It would have failed for any contractor whose time zone isn't UTC.

Tests run on real PostgreSQL

That last bug is why the functional tests don't use EF's in-memory provider or SQLite. Neither appears anywhere in the repository. The suite, about three hundred tests, starts a real PostgreSQL through .NET Aspire's test host and resets the data with Respawn before every test.

That setup had a bug of its own:

var respawner = await Respawner.CreateAsync(connection, new RespawnerOptions
{
    DbAdapter = DbAdapter.Postgres,
    // The reset must leave the schema as migrated. Clearing the history
    // table makes the next process re-apply every migration onto tables
    // that already exist, which only shows once a database is reused.
    TablesToIgnore = [new Table("__EFMigrationsHistory")],
});

Respawn empties every table, and at first that included EF's own migration history. With a fresh container on each run nobody noticed. As soon as I pointed the tests at a database that persisted between runs, the next start tried to apply all the migrations again on top of tables that already existed, and failed before a single test ran.

There's one more kind of test worth mentioning. A small set builds the EF model with the Npgsql provider and asserts on column types, indexes and delete behaviour without ever opening a connection. They need no database, and they catch a mapping mistake before it turns into a surprising migration.

The migration trap

This one has nothing to do with Dapper, and it's the EF problem that worried me most.

The app applied migrations at startup, but only when the environment was named Development or Staging. Then I thought about launch day. Someone renames the environment to Production. The app boots. Migrations quietly don't run.

I tested it on a clean database to see how bad it was. The app started and the liveness endpoint returned 200, with zero tables in the database.

Now the decision is a setting of its own:

// Whether this instance applies migrations as it starts is a setting, not a
// consequence of the environment's name: Database:MigrateOnStartup decides,
// and only when it is unset does the name (Development or Staging) stand in.
if (app.Configuration.GetValue<bool?>("Database:MigrateOnStartup")
    ?? (app.Environment.IsDevelopment() || app.Environment.IsStaging()))
{
    await app.MigrateDatabaseAsync();
}

Migrating at startup is only safe while the app runs as a single replica, because two instances starting together would race each other. The runbook says to switch to an idempotent SQL script before scaling out.

What would make me add Dapper

I haven't yet had a query that justified a second way of talking to the database. These would:

  • The dashboard's in-memory grouping outgrows its ceiling, and I need window functions or percentiles in SQL.
  • A measured endpoint spends its time in round trips that could be batched into one.
  • A report needs a query I can write in SQL in ten minutes and can't get out of LINQ in an hour.

The request pipeline already logs anything that takes longer than 500ms, so I'll have somewhere to look when one of these happens.

If you're starting a new .NET service, my suggestion is to leave Dapper out at first. Turn tracking off for reads, project to the columns you use, use ExecuteUpdate and ExecuteDelete for bulk changes, and run your tests against the real database. Add the second library on the day you can name the query that needs it.