Parameters and result mapping
Parameters and result mapping
Parameters keep data values separate from SQL syntax. Write a constant query containing placeholders, then bind values through the provider parameter collection. This prevents a value such as a name containing an apostrophe from being interpreted as SQL code. Map database values to C# types explicitly, especially when a column allows SQL NULL.
Proposed baseline: .NET SDK 10.0.404, net10.0 / C# 14. Requires reviewed Microsoft.Data.Sqlite 10.0.15 candidate package and native dependencies. All databases are private in-memory fixtures; no network or disk database. C# results are reasoned, not executed. See the accompanying independent project fixture; approve dependencies and environment before restoring or building.
Bind text containing an apostrophe
Use a parameter for a book title. The apostrophe is ordinary data, not syntax.
using System;using Microsoft.Data.Sqlite;using var db = new SqliteConnection("Data Source=:memory:;Pooling=False");db.Open();using var cmd = db.CreateCommand();cmd.CommandText = "CREATE TABLE Books (Title TEXT NOT NULL)";cmd.ExecuteNonQuery();cmd.CommandText = "INSERT INTO Books VALUES ($title)";cmd.Parameters.AddWithValue("$title", "Reader's guide");cmd.ExecuteNonQuery();cmd.CommandText = "SELECT Title FROM Books WHERE Title = $title";Console.WriteLine(cmd.ExecuteScalar());The placeholder stays in the SQL text. The value is supplied by the parameter collection; no manual escaping or string concatenation is required.
Expected observation (reasoned, not executed):
Reader's guideMap an optional database field
The reader exposes SQL NULL through IsDBNull. A nullable C# string represents a missing note in the DTO.
using System;using Microsoft.Data.Sqlite;using var db = new SqliteConnection("Data Source=:memory:;Pooling=False");db.Open();using var cmd = db.CreateCommand();cmd.CommandText = "CREATE TABLE Books (Id INTEGER PRIMARY KEY, Note TEXT NULL)";cmd.ExecuteNonQuery();cmd.CommandText = "INSERT INTO Books VALUES (1, NULL), (2, '')";cmd.ExecuteNonQuery();cmd.CommandText = "SELECT Id, Note FROM Books ORDER BY Id";using var reader = cmd.ExecuteReader();while (reader.Read()){ var book = new Book(reader.GetInt64(0), reader.IsDBNull(1) ? null : reader.GetString(1)); Console.WriteLine($"{book.Id}: {(book.Note is null ? "missing" : $"length {book.Note.Length}")}");}public sealed record Book(long Id, string? Note);NULL and an empty string have different meanings. The reader checks the null marker before calling the typed accessor.
Expected observation (reasoned, not executed):
1: missing2: length 0Allowlist a sort column
Placeholders bind values, not SQL identifiers. Select a fixed trusted fragment from a small explicit mapping.
using System;using Microsoft.Data.Sqlite;using var db = new SqliteConnection("Data Source=:memory:;Pooling=False");db.Open();using var cmd = db.CreateCommand();cmd.CommandText = "CREATE TABLE Books (Id INTEGER PRIMARY KEY, Title TEXT NOT NULL)";cmd.ExecuteNonQuery();cmd.CommandText = "INSERT INTO Books VALUES (1, 'Zebra'), (2, 'Apple')";cmd.ExecuteNonQuery();string requested = "title";string column = requested switch{ "title" => "Title", "id" => "Id", _ => throw new ArgumentException("Unknown sort key")};cmd.CommandText = $"SELECT Title FROM Books ORDER BY {column}, Id";using var reader = cmd.ExecuteReader();while (reader.Read()) Console.WriteLine(reader.GetString(0));Only hardcoded fragments enter SQL structure. Reject unknown sort keys; never concatenate the original input. The ID tie-breaker makes ordering deterministic.
Expected observation (reasoned, not executed):
AppleZebraCommon mistakes and edge cases
Use named parameters in Microsoft.Data.Sqlite; other providers may use different placeholder rules and typed parameter APIs. Assign DBNull.Value for a SQL NULL parameter, not a C# null reference as the parameter value. SQLite storage classes and type affinity differ from PostgreSQL and SQL Server; mapping a field as long is appropriate for the integer fixture, not a universal mapping for every SQL numeric type. Parameters cannot substitute table names, column names or keywords. Validate and authorize queries separately: parameterization alone does not grant correct access control.
Practice and recap
Write a parameterized lookup for an optional note by integer ID. Explain how to represent no row, NULL note and empty note distinctly. Add a rejected sort-key case.
Hint: Use Read before accessing a row.
Learning objective: Separate SQL text from values. See accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Parameters and result mapping — knowledge check
Apply the lesson concepts to the following scenarios.
How should an apostrophe in a title be supplied?
What checks a nullable database column?
How should a dynamic sort column be selected?
How do you represent SQL NULL as a parameter value?
Does parameter binding enforce authorization?