IC Improve Code Recipes

Recipe 1.4 · C#

Mapping Readers to Objects, and When to Use Dapper

Problem

Hand-written mapping is where silent data bugs live. Code that reads reader[3] breaks when someone adds a column to the view. Code that casts (string)reader["Notes"] throws the first time a row has a NULL. Code that calls GetOrdinal inside the loop pays for a name lookup on every row of a million-row export.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not to copy: positional, null-unsafe, untyped.
while (reader.Read())
{
    Order o = new Order();
    o.OrderId = Convert.ToInt32(reader[0]);
    o.CustomerName = reader[1].ToString();
    o.OrderedOn = Convert.ToDateTime(reader[2]);
    o.Total = Convert.ToDecimal(reader[3]);
    o.Notes = (string)reader["Notes"];  // throws on NULL
    list.Add(o);
}

The improved recipe

C#
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;

namespace ImproveCode.Data;

public sealed record OrderRow(
    int OrderId,
    string CustomerName,
    DateTime OrderedUtc,
    decimal Total,
    string? Notes);

public static class OrderRowReader
{
    public static async Task<List<OrderRow>> ReadAllAsync(
        SqlDataReader reader, CancellationToken ct = default)
    {
        int id = reader.GetOrdinal("OrderId");
        int name = reader.GetOrdinal("CustomerName");
        int ordered = reader.GetOrdinal("OrderedUtc");
        int total = reader.GetOrdinal("Total");
        int notes = reader.GetOrdinal("Notes");

        var rows = new List<OrderRow>();
        while (await reader.ReadAsync(ct))
        {
            rows.Add(new OrderRow(
                reader.GetInt32(id),
                reader.GetString(name),
                reader.GetDateTime(ordered),
                reader.GetDecimal(total),
                reader.IsDBNull(notes)
                    ? null
                    : reader.GetString(notes)));
        }
        return rows;
    }
}

And the same query with Dapper:

C#
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Dapper;

namespace ImproveCode.Data;

public sealed class OrderQueries(IDbConnectionFactory db)
{
    private const string RecentSql = """
        SELECT TOP (@Max)
               o.OrderId, c.Name AS CustomerName, o.OrderedUtc,
               o.Total, o.Notes
        FROM dbo.SalesOrder AS o
        JOIN dbo.Customer AS c ON c.CustomerId = o.CustomerId
        WHERE o.CustomerId = @CustomerId
        ORDER BY o.OrderedUtc DESC;
        """;

    public async Task<IReadOnlyList<OrderRow>> RecentAsync(
        int customerId, int max = 50, CancellationToken ct = default)
    {
        await using var connection = await db.OpenAsync(ct);
        var command = new CommandDefinition(
            RecentSql,
            new { CustomerId = customerId, Max = max },
            cancellationToken: ct);
        IEnumerable<OrderRow> rows =
            await connection.QueryAsync<OrderRow>(command);
        return rows.AsList();
    }
}

How it works

The hand-written reader looks up each ordinal by name once, before the loop, then uses the typed getters (GetInt32, GetString, GetDecimal) inside it. Lookup by name protects you from column-order changes. Typed getters throw a clear InvalidCastException if the SQL type changes, rather than converting silently. IsDBNull is checked only for the columns that are nullable in the database, which documents the schema in the code: Notes is string? in the record because it is nullable in the table.

Dapper does the same work for you. It matches column names to the record's constructor parameters, case-insensitively, and generates and caches the mapping code per query and type. Its anonymous-object parameters are convenient, and CommandDefinition is how you pass a cancellation token.

My rule: use Dapper when a project has more than a handful of queries and nobody objects to one small dependency. Write the reader code by hand when you are in a library that must stay dependency-free, when you need CommandBehavior.SequentialAccess for large columns, or when you are mapping one or two queries and a dependency is not worth it. Both are far better than DataSet.

Variations and pitfalls

  • Dapper strings default to nvarchar(4000). For a varchar column, pass new DbString { Value = email, IsAnsi = true, Length = 254 } instead of a plain string, for the same plan-cache and conversion reasons as Recipe 1.2.
  • Constructor matching is strict. For a positional record, Dapper needs a column for every constructor parameter with a compatible type. A BIGINT column will not bind to an int parameter. Use a class with settable properties if your columns and properties do not line up exactly.
  • GetDateTime and DATETIMEOFFSET. A DATETIMEOFFSET column needs GetFieldValue<DateTimeOffset>. GetFieldValue<T> also works for DateOnly and TimeOnly with DATE and TIME columns in recent versions of Microsoft.Data.SqlClient.
  • Entity Framework Core is a fine choice for a new application with a domain model. This chapter is about the many applications that already have SQL and stored procedures and need a cleaner way to call them.