Dapper mapping and parameters
Dapper mapping and parameters
Dapper maps result columns to requested scalar or object members. Mapping is an explicit contract between the SELECT list and the destination type. Aliases help express that contract. Bind values through parameters instead of constructing SQL text from user input, and choose a query method that enforces the expected number of rows.
Proposed baseline: .NET 10 / C# 14 (SDK 10.0.404 inherited). Private SQLite in-memory fixture, Dapper 2.1.100 or EF Core SQLite 10.0.15 candidate dependencies. Approve dependencies before restore; no external database needed. Outputs are reasoned, not executed.
Map a joined result with aliases
Use a left join so a book with no shelf still appears. The destination property is nullable.
using System;using System.Linq;using Dapper;using Microsoft.Data.Sqlite;using var db = new SqliteConnection("Data Source=:memory:;Pooling=False");db.Open();db.Execute("CREATE TABLE Shelves (Id INTEGER PRIMARY KEY, Label TEXT NOT NULL)");db.Execute("CREATE TABLE Books (Id INTEGER PRIMARY KEY, Title TEXT NOT NULL, ShelfId INTEGER REFERENCES Shelves(Id))");db.Execute("INSERT INTO Shelves VALUES (1, 'A1')");db.Execute("INSERT INTO Books VALUES (1, 'Atlas', 1), (2, 'Notebook', NULL)");var rows = db.Query<BookRow>("SELECT b.Title AS Title, s.Label AS Shelf FROM Books b LEFT JOIN Shelves s ON b.ShelfId = s.Id ORDER BY b.Id");foreach (var row in rows) Console.WriteLine($"{row.Title}: {row.Shelf ?? "unassigned"}");public class BookRow { public string Title { get; set; } = ""; public string? Shelf { get; set; } }The unmatched shelf produces SQL NULL; the nullable property preserves the absence instead of inventing a shelf.
Expected observation (reasoned, not executed):
Atlas: A1Notebook: unassignedBind text containing an apostrophe
Supply an anonymous object with a Title property. The SQL string never contains the actual search text.
using System;using System.Linq;using Dapper;using Microsoft.Data.Sqlite;using var db = new SqliteConnection("Data Source=:memory:;Pooling=False");db.Open();db.Execute("CREATE TABLE Books (Id INTEGER PRIMARY KEY, Title TEXT NOT NULL, Stock INTEGER NOT NULL CHECK(Stock >= 0))");db.Execute("INSERT INTO Books VALUES (1, 'Atlas', 4), (2, 'Notebook', 1)");db.Execute("INSERT INTO Books VALUES (3, @Title, 2)", new { Title = "Reader's guide" });Console.WriteLine(db.QuerySingle<string>("SELECT Title FROM Books WHERE Title = @Title", new { Title = "Reader's guide" }));The apostrophe is data rather than SQL syntax. Parameters protect values, not arbitrary identifiers or SQL fragments.
Expected observation (reasoned, not executed):
Reader's guideEnforce cardinality
Try a missing row and then a query with multiple matches. Use a nullable reference result to distinguish missing data.
using System;using System.Linq;using Dapper;using Microsoft.Data.Sqlite;using var db = new SqliteConnection("Data Source=:memory:;Pooling=False");db.Open();db.Execute("CREATE TABLE Books (Id INTEGER PRIMARY KEY, Title TEXT NOT NULL, Stock INTEGER NOT NULL CHECK(Stock >= 0))");db.Execute("INSERT INTO Books VALUES (1, 'Atlas', 4), (2, 'Notebook', 1)");var missing = db.QuerySingleOrDefault<string>("SELECT Title FROM Books WHERE Id = @Id", new { Id = 99 });Console.WriteLine(missing is null);try { db.QuerySingle<string>("SELECT Title FROM Books"); }catch (InvalidOperationException) { Console.WriteLine("Multiple rows"); }SingleOrDefault allows zero or one row; Single rejects both zero and multiple rows. First methods have different multiplicity rules.
Expected observation (reasoned, not executed):
TrueMultiple rowsCommon mistakes and edge cases
An unmatched nonnullable value property may remain at a default value rather than visibly fail, depending on mapping and constructor choices. Use explicit aliases and tests for missing columns and NULL. QuerySingleOrDefault<int> returns zero for no row, which can be ambiguous; choose a nullable scalar or result object when needed. For dynamic sort columns use an allowlist of constant SQL fragments; a value parameter cannot substitute a column identifier.
Practice and recap
Extend the join to find a book by ID. Test ID 1, ID 2 and a missing ID. Explain how missing book differs from missing shelf.
Hint: Use a nullable BookRow result.
Learning objective: Identify null, alias and multiplicity assumptions. See accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dapper mapping and parameters — knowledge check
Apply the lesson concepts to the following scenarios.
Why alias s.Label AS Shelf?
What should represent a missing shelf?
Which method allows zero or one row?
How should an apostrophe-containing title be sent?
How should user-selected sort columns be handled?