Recipe 1.2 · C#
Parameterized Queries, Typed Properly
Problem
SQL built by string concatenation is the oldest security hole in the business-application world, and it is still being written. Even teams that know to use parameters often use them loosely, with AddWithValue, and pay for it in slow queries and a bloated plan cache.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: injection, quoting bugs and no plan reuse.
string sql = "SELECT CustomerId, Name, Email FROM Customer " +
"WHERE Email = '" + txtEmail.Text + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
// Better, but still loose: type and length are guessed.
cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
The first version breaks on the first customer named O'Brien and hands the database to anyone who types ' OR 1=1 --. The second version is safe from injection, but AddWithValue infers an nvarchar parameter with a length equal to the string. A 12-character e-mail gets nvarchar(12), a 13-character one gets nvarchar(13), and each produces its own cached plan. If the column is varchar, SQL Server must convert every row of the column to compare against an nvarchar value, which can turn an index seek into a scan.
The improved recipe
using System;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
namespace ImproveCode.Data;
public static class SqlParameterExtensions
{
public static SqlParameter AddInt(
this SqlParameterCollection p, string name, int? value) =>
p.Add(name, SqlDbType.Int).WithValue(value);
public static SqlParameter AddVarChar(
this SqlParameterCollection p, string name, int size,
string? value) =>
p.Add(name, SqlDbType.VarChar, size).WithValue(value);
public static SqlParameter AddNVarChar(
this SqlParameterCollection p, string name, int size,
string? value) =>
p.Add(name, SqlDbType.NVarChar, size).WithValue(value);
public static SqlParameter AddDecimal(
this SqlParameterCollection p, string name,
byte precision, byte scale, decimal? value)
{
SqlParameter parameter = p.Add(name, SqlDbType.Decimal);
parameter.Precision = precision;
parameter.Scale = scale;
return parameter.WithValue(value);
}
public static SqlParameter AddDateTime2(
this SqlParameterCollection p, string name,
DateTime? value) =>
p.Add(name, SqlDbType.DateTime2).WithValue(value);
private static SqlParameter WithValue(
this SqlParameter parameter, object? value)
{
parameter.Value = value ?? DBNull.Value;
return parameter;
}
}
public sealed record CustomerSummary(int Id, string Name, string Email);
public sealed class CustomerLookup(IDbConnectionFactory db)
{
private const string FindByEmailSql = """
SELECT CustomerId, Name, Email
FROM dbo.Customer
WHERE Email = @Email AND IsActive = 1;
""";
public async Task<CustomerSummary?> FindByEmailAsync(
string email, CancellationToken ct = default)
{
await using var connection = await db.OpenAsync(ct);
await using var command =
new SqlCommand(FindByEmailSql, connection);
command.Parameters.AddVarChar("@Email", 254, email);
await using var reader = await command.ExecuteReaderAsync(ct);
if (!await reader.ReadAsync(ct))
{
return null;
}
return new CustomerSummary(
reader.GetInt32(0),
reader.GetString(1),
reader.GetString(2));
}
}
How it works
Each extension method creates a parameter with an explicit SqlDbType, and a size, precision or scale where the type needs one. Declare the parameter exactly like the column it is compared against. A varchar(254) column gets a varchar(254) parameter, so SQL Server sees the same parameter signature on every call and reuses one plan.
The private WithValue helper converts a C# null into DBNull.Value. Forgetting that conversion is a classic bug: a parameter whose Value is null is treated as not supplied, and the call fails with an error about a missing parameter.
The query text is a constant, written as a raw string literal so it reads like SQL. Nothing from the user ever touches it.
Variations and pitfalls
- Identifiers cannot be parameters. You cannot pass a column name for
ORDER BYor a table name as a parameter. Map user choices to known names through a whitelist and reject anything else:
// Usage snippet: sort column whitelist.
private static readonly Dictionary<string, string> SortColumns =
new(StringComparer.OrdinalIgnoreCase)
{
["name"] = "Name",
["created"] = "CreatedUtc"
};
string column = SortColumns.TryGetValue(sort, out var c)
? c : "Name";
- IN lists. Do not build
IN (1, 2, 3)by joining strings. Pass a table-valued parameter (Recipe 1.6), or let Dapper expand a list parameter for you. LIKEsearches. Parameterize the pattern and add the wildcards in C#:"%" + term + "%". If the term itself can contain%,_or[, escape those characters first.- Stored procedures. Set
CommandType.StoredProcedureand pass the procedure name as the command text. The same typed parameters apply.