Dapper
Dapper is a small .NET object mapper that executes explicit, parameterized SQL through standard ADO.NET connections and maps result rows to focused application types.
Overview
Dapper adds convenient query, command, parameter, multi-mapping, and multiple-result APIs to DbConnection without taking ownership of the relational model. The application still owns SQL text, projections, connection lifetime, transaction boundaries, schema evolution, provider behavior, indexes, query plans, and failure handling. That explicitness makes Dapper a strong fit for read models, reporting, CQRS query paths, stored procedures, and performance-sensitive operations where the team wants precise SQL control. It also means production-ready code must allowlist dynamic identifiers, parameterize every value, bound result sets, propagate cancellation, coordinate transactions deliberately, test against the real database provider, and operate schema changes outside Dapper itself.
What you will learn
- Explain what Dapper adds to ADO.NET and which responsibilities remain with the application and database.
- Choose the correct Query, Execute, single-row, scalar, multi-mapping, and multiple-result API for a use case.
- Write parameterized SQL while handling dynamic filters, sort columns, directions, and identifiers through trusted allowlists.
- Own connection and transaction lifetimes so related commands commit or roll back atomically.
- Design bounded projections, stable pagination, indexes, timeouts, and diagnostics for important query paths.
- Test mappings, constraints, transactions, and provider-specific SQL against a real relational database.
Prerequisites
- Comfort with C#, async and await, cancellation tokens, records or DTOs, and dependency injection.
- Working knowledge of SQL including joins, grouping, indexes, parameters, transactions, and query plans.
- The .NET 10 SDK; the dedicated sample uses SQLite and does not require Docker.
When to use Dapper
Good fit
- Read-heavy features where explicit SQL and narrow result shapes are easier to reason about than ORM query translation.
- CQRS query paths, reports, stored procedures, legacy schemas, or hot operations that need precise provider-specific SQL.
- Teams with strong SQL ownership that want lightweight row mapping while retaining direct ADO.NET control.
Choose another approach when
- Aggregate-heavy transactional applications that benefit from identity tracking, relationship fix-up, change detection, and managed migrations; EF Core may remove substantial ceremony.
- A team that cannot own SQL review, schema deployment, provider-specific tests, and query-plan analysis as part of normal delivery.
- An abstraction intended to make one SQL implementation portable across different database engines without deliberate dialect and behavior work.
Key concepts
The application owns query text, joins, projections, indexes, and provider behavior rather than relying on a LINQ translator.
A command packages SQL, parameters, transaction, timeout, command type, flags, and a cancellation token for an asynchronous operation.
Anonymous objects, POCOs, dictionaries, lists, and DynamicParameters bind values without concatenating them into SQL text.
Query, QueryFirst, QuerySingle, Execute, and ExecuteScalar express different expectations; selecting the right API makes missing or duplicate rows visible.
Column aliases map rows to typed objects, while splitOn-based multi-mapping folds joined records into object graphs intentionally.
QueryMultiple consumes several result grids from one command, reducing round trips when the results belong to one coherent read operation.
The application opens and disposes connections and must pass the same connection and transaction to every statement that must be atomic.
Dapper does not normalize SQL syntax, types, locking, stored procedures, or plans; the selected ADO.NET provider and database define behavior.
Architecture
An application query or command selects reviewed SQL and parameters. Dapper executes through an opened provider connection and optional transaction, the database applies constraints and a query plan, and Dapper materializes explicit result types.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
Build the SQL boundary explicitly, then prove mapping, constraints, transaction behavior, and query shape against a relational provider.
- 01Choose the provider and SQL dialect
Install Dapper plus the ADO.NET provider for the production database, and define where provider-specific SQL is allowed to live.
- 02Define result and command models
Create narrow types whose names and nullability match the selected columns and expected cardinality rather than mapping entire tables automatically.
- 03Write parameterized, bounded SQL
Alias columns intentionally, bind every value, apply deterministic ordering, cap page size, and avoid SELECT star on application paths.
- 04Allowlist dynamic structure
Map sort choices, directions, table names, or optional SQL fragments from trusted enums or constants because identifiers cannot be command parameters.
- 05Own connections and transactions
Open connections late, dispose them promptly, and pass one transaction object to every command that forms an atomic unit.
- 06Handle relationships deliberately
Use multi-mapping for joined rows or QueryMultiple for coherent result grids, then de-duplicate parent objects in application code.
- 07Test and measure the database path
Verify mappings, constraints, rollback, cancellation, indexes, plans, row counts, and latency against the target provider with production-shaped data.
Code example
The dedicated sample binds filter values, caps pagination, propagates cancellation, and selects an ORDER BY clause only from trusted enum-backed constants.
private static readonly IReadOnlyDictionary<OrderSort, string> SortClauses =
new Dictionary<OrderSort, string>
{
[OrderSort.Newest] = "o.created_at_unix_seconds DESC, o.id",
[OrderSort.Oldest] = "o.created_at_unix_seconds ASC, o.id",
[OrderSort.HighestValue] = "TotalCents DESC, o.id"
};
var orderBy = SortClauses[search.Sort];
var sql = string.Format(CultureInfo.InvariantCulture, SearchSql, orderBy);
var command = new CommandDefinition(
sql,
new
{
search.Status,
search.MinimumTotalCents,
search.PageSize,
Offset = checked(search.Page * search.PageSize)
},
cancellationToken: cancellationToken);
return (await connection.QueryAsync<OrderSummary>(command)).AsList();Testing strategy
Dapper tests must execute real SQL because mapping, constraints, transaction behavior, and dialect rules do not exist in an in-memory collection.
- Create an isolated relational database per test or test collection and apply the same reviewed schema used by the application.
- Assert result cardinality, aliases, null handling, numeric and time representations, and multi-mapping boundaries.
- Force constraint failures after an earlier write and prove the entire transaction rolls back.
- Test allowlisted dynamic sort choices, stable pagination, bounded page sizes, timeouts, and cancellation behavior.
- Run critical queries against the production provider and inspect plans with representative row counts; SQLite is valuable but cannot prove PostgreSQL or SQL Server behavior.
Security considerations
Dapper makes value parameters convenient, but application-owned SQL remains a security boundary.
- Bind all untrusted values; never interpolate or concatenate search text, IDs, dates, or numeric values into SQL.
- Map dynamic identifiers, columns, directions, and fragments from strict server-owned allowlists because they cannot be parameters.
- Use a least-privilege runtime database identity and a separate controlled identity for schema deployment.
- Authorize resource and tenant access before executing a query, and make tenant predicates non-optional in shared data stores.
- Do not log secrets or raw personal parameters; record normalized operation names, duration, row count, timeout, and correlation context instead.
Performance and scalability
Dapper minimizes mapping overhead, but database work, network round trips, result size, locks, and query plans dominate most production paths.
- Select only required columns, cap every collection, use deterministic pagination, and stream only when connection lifetime and backpressure are understood.
- Measure generated plans, logical reads, row estimates, duration, round trips, and allocation before choosing a micro-ORM for speed.
- Create indexes for measured predicates and ordering, while accounting for write amplification and maintenance cost.
- Use QueryMultiple only for coherent results and avoid giant joins whose repeated parent columns cause excessive transfer and de-duplication work.
- Set realistic command timeouts, propagate cancellation, and keep transactions short so pooled connections and locks are released quickly.
Deployment and operations
Dapper does not create or migrate schemas, so database change delivery needs an explicit operational owner and toolchain.
- Version schema scripts or use a migration tool, review changes as code, and test them against production-like data volume.
- Deploy schema changes from one controlled job rather than allowing every application instance to race at startup.
- Use expand-and-contract migrations when old and new application versions overlap, especially for renamed or newly required columns.
- Pin and audit Dapper, the ADO.NET provider, native database dependencies, and migration tooling as a compatible set.
- Back up data, rehearse forward-fix and rollback procedures, monitor locks and duration, and verify application mappings immediately after deployment.
Common problems and fixes
A query returns default values or mapping throws.
Likely cause: Selected column names, aliases, nullability, or database types do not match the target constructor or properties.
Fix: Select explicit columns, alias them to the model, inspect provider-returned types, and add an integration test for the exact row shape.
A dynamic query is vulnerable or fails for some sort choices.
Likely cause: User input was concatenated into a column, direction, identifier, or SQL fragment that cannot be parameterized.
Fix: Translate a validated enum or fixed key to a server-owned SQL constant and reject every unknown value.
A transaction partially commits.
Likely cause: One command used another connection, omitted the transaction argument, or committed outside the intended unit of work.
Fix: Create one connection and transaction at the service boundary, pass both to every Dapper command, and prove rollback with a forced constraint failure.
Multi-mapping creates duplicate parents or empty children.
Likely cause: The splitOn column is wrong, join rows repeat the parent, or the aggregation callback does not use an identity lookup.
Fix: Alias the split column explicitly, use a parent-key dictionary, add each child once, and test zero, one, and many child rows.
A fast local query is slow in production.
Likely cause: Production data volume, indexes, provider behavior, network latency, blocking, or the selected plan differs from the local environment.
Fix: Capture the production-shaped plan and telemetry, compare parameters and row counts, then correct query shape or indexes based on evidence.
Best practices
- Always bind changing values as parameters; never concatenate untrusted input into SQL.
- Allowlist dynamic identifiers, columns, directions, and fragments with enums or fixed server-owned mappings.
- Project only required columns, cap result sizes, use stable ordering, and inspect query plans for important paths.
- Choose Query, QuerySingle, QueryFirst, Execute, or ExecuteScalar to match the expected result cardinality.
- Open connections late, dispose them promptly, and pass the same explicit transaction to every atomic command.
- Use CommandDefinition for cancellation, timeouts, command types, and transaction context where the selected API supports it.
- Keep SQL and mapping tests close to the production provider because dialects, types, casing, locking, and plans differ.
- Manage schema evolution through reviewed scripts or migration tooling; Dapper is not a schema manager.
Production checklist
- All values are parameters, and every dynamic identifier or fragment comes from a closed server-owned allowlist.
- Queries select explicit columns, enforce bounded results, use stable ordering, and have reviewed indexes and plans.
- Connection, transaction, timeout, cancellation, and disposal ownership is visible at each application boundary.
- Expected zero, one, and many-row cardinalities use the matching Dapper API and have mapping tests.
- Atomic workflows have commit and forced-rollback integration tests against a relational provider.
- Schema changes are versioned, reviewed, deployed once, backward-compatible during rollout, and observable.
- Critical SQL is tested against the production engine with representative data and safe diagnostic logging.
Common interview questions
How is Dapper different from EF Core?
Dapper maps explicit SQL over ADO.NET and provides little unit-of-work or change-tracking behavior. EF Core supplies LINQ translation, identity and change tracking, relationships, migrations, and a richer ORM model.
Can Dapper and EF Core be used together?
Yes. A common CQRS approach uses EF Core for transactional writes and Dapper for explicit read projections, provided connection and transaction ownership are coordinated when atomicity is required.
Does using Dapper automatically prevent SQL injection?
No. Dapper makes parameter binding convenient, but dynamic SQL built by concatenating untrusted input is still vulnerable. Dynamic identifiers and sort choices require allowlists.
Why use CommandDefinition?
It packages SQL with parameters, a transaction, timeout, command type, flags, and cancellation token, making execution policy explicit for supported APIs.
When should QueryMultiple or multi-mapping be used?
Use QueryMultiple for several coherent result grids in one command. Use multi-mapping when one joined row contains columns for multiple objects, then de-duplicate parent objects deliberately.
Who owns migrations and transactions when using Dapper?
The application and its delivery tooling do. Dapper executes against the supplied connection and transaction and does not track a model or generate schema migrations.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
Dapper Order Reporting
A focused .NET 10 console sample demonstrating parameterized SQL, allowlisted dynamic sorting, bounded pagination, multi-mapping, multiple result sets, explicit connection and transaction ownership, relational constraints, and real SQLite integration tests.
- Run
dotnet run --project src/DapperOrderReporting- Test
dotnet test DapperOrderReporting.slnx