Recipe 1.4 · Python
Mapping Readers to Objects, and When to Use Dapper
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
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.
Requirements: Python 3.12+. Install: pip install pyodbc · Needs at run time: SQL Server + Microsoft ODBC Driver 18 for SQL Server. The module loads without them; calling the code does not work without them.
"""Positional, null-unsafe row mapping
Source: ImproveCode, Chapter 1, Recipe 1.4 "Mapping Readers to Objects, and When to Use Dapper"
Section: The way it's often written
Book page: 26 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
SqlDataReader -> pyodbc cursor rows; the (string) cast that throws on NULL becomes an
explicit isinstance check that raises TypeError on None, matching the C# failure.
"""
from datetime import datetime
from decimal import Decimal
from typing import Any
import pyodbc
class Order:
def __init__(self) -> None:
self.order_id: int = 0
self.customer_name: str = ""
self.ordered_on: datetime | None = None
self.total: Decimal = Decimal(0)
self.notes: str = ""
def _cast_str(value: Any) -> str:
if not isinstance(value, str):
raise TypeError("cannot cast to str")
return value
def read_orders(reader: pyodbc.Cursor, lst: list[Order]) -> None:
# Not to copy: positional, null-unsafe, untyped.
for row in reader:
o = Order()
o.order_id = int(row[0])
o.customer_name = str(row[1])
o.ordered_on = row[2]
o.total = Decimal(row[3])
o.notes = _cast_str(row.Notes) # throws on NULL
lst.append(o)
The improved recipe
And the same query with Dapper:
Requirements: Python 3.12+. Install: pip install sqlalchemy greenlet
"""Recent orders query mapped by a micro-ORM (Dapper equivalent)
Source: ImproveCode, Chapter 1, Recipe 1.4 "Mapping Readers to Objects, and When to Use Dapper"
Section: The improved recipe
Book page: 26-27 -- original C# listing
Converted from C# to Python.
Dapper -> SQLAlchemy Core text() over an AsyncEngine ("mssql+aioodbc://..."), which binds named
parameters (:Max, :CustomerId) and returns rows whose ._mapping is mapped onto the frozen
dataclass by column name, as Dapper does.
"""
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncEngine
@dataclass(frozen=True)
class OrderRow:
OrderId: int
CustomerName: str
OrderedUtc: datetime
Total: Decimal
Notes: str | None
class OrderQueries:
RECENT_SQL = text("""
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;
""")
def __init__(self, db: AsyncEngine) -> None:
self._db = db
async def recent(self, customer_id: int, max: int = 50) -> list[OrderRow]:
async with self._db.connect() as connection:
result = await connection.execute(
self.RECENT_SQL, {"CustomerId": customer_id, "Max": max})
return [OrderRow(**row._mapping) for row in result]
Requirements: Python 3.12+. Install: pip install aioodbc · Needs at run time: SQL Server + Microsoft ODBC Driver 18 for SQL Server. The module loads without them; calling the code does not work without them.
"""Map reader rows to an immutable record by column name
Source: ImproveCode, Chapter 1, Recipe 1.4 "Mapping Readers to Objects, and When to Use Dapper"
Section: The improved recipe
Book page: 26-27 -- original C# listing
Converted from C# to Python.
record -> frozen dataclass; GetOrdinal -> index lookup in cursor.description (aioodbc cursor);
IsDBNull -> None check.
"""
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
import aioodbc
@dataclass(frozen=True)
class OrderRow:
order_id: int
customer_name: str
ordered_utc: datetime
total: Decimal
notes: str | None
class OrderRowReader:
@staticmethod
async def read_all(reader: aioodbc.Cursor) -> list[OrderRow]:
ordinals = {col[0]: i for i, col in enumerate(reader.description)}
id_ = ordinals["OrderId"]
name = ordinals["CustomerName"]
ordered = ordinals["OrderedUtc"]
total = ordinals["Total"]
notes = ordinals["Notes"]
rows: list[OrderRow] = []
while (r := await reader.fetchone()) is not None:
rows.append(OrderRow(
int(r[id_]),
str(r[name]),
r[ordered],
Decimal(r[total]),
None if r[notes] is None else str(r[notes])))
return rows
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 avarcharcolumn, passnew 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
BIGINTcolumn will not bind to anintparameter. Use a class with settable properties if your columns and properties do not line up exactly. GetDateTimeandDATETIMEOFFSET. ADATETIMEOFFSETcolumn needsGetFieldValue<DateTimeOffset>.GetFieldValue<T>also works forDateOnlyandTimeOnlywithDATEandTIMEcolumns in recent versions ofMicrosoft.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.