Recipe 1.3 · C#
A Small Data Helper to Replace SqlHelper
- Problem
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
The classic SqlHelper that many teams copied came from Microsoft's Data Access Application Block, released in 2002 for .NET Framework 1.0. It was useful at the time. It is now a liability: synchronous only, built around DataSet, overloads that take an open connection or a connection string or a transaction in every combination, and params object[] parameter lists that hide types. Teams keep it because removing it feels like a big job.
You do not need a large replacement. You need the three operations you actually use, with typed parameters and async.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: the typical SqlHelper-style call.
DataSet ds = SqlHelper.ExecuteDataset(
connString, CommandType.Text,
"SELECT Name FROM Region WHERE CountryCode = '" + code + "'");
foreach (DataRow row in ds.Tables[0].Rows)
{
names.Add(row[0].ToString());
}
This shape is everywhere: about 9,585 files in the archive create a DataSet or DataTable, across 30 engagements. Everything is loaded into a DataSet, the values come back as object, and the static method encourages string-built SQL because parameters are awkward to pass.
The improved recipe
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
namespace ImproveCode.Data;
public sealed class Db(IDbConnectionFactory factory)
{
public int CommandTimeoutSeconds { get; init; } = 30;
public async Task<int> ExecuteAsync(
string sql,
Action<SqlParameterCollection>? parameters = null,
CommandType type = CommandType.Text,
CancellationToken ct = default)
{
await using var connection = await factory.OpenAsync(ct);
await using var command =
Create(connection, sql, type, parameters);
return await command.ExecuteNonQueryAsync(ct);
}
public async Task<T?> ScalarAsync<T>(
string sql,
Action<SqlParameterCollection>? parameters = null,
CommandType type = CommandType.Text,
CancellationToken ct = default)
{
await using var connection = await factory.OpenAsync(ct);
await using var command =
Create(connection, sql, type, parameters);
object? value = await command.ExecuteScalarAsync(ct);
return value is null or DBNull ? default : (T)value;
}
public async Task<List<T>> QueryAsync<T>(
string sql,
Func<SqlDataReader, T> map,
Action<SqlParameterCollection>? parameters = null,
CommandType type = CommandType.Text,
CancellationToken ct = default)
{
await using var connection = await factory.OpenAsync(ct);
await using var command =
Create(connection, sql, type, parameters);
await using var reader = await command.ExecuteReaderAsync(ct);
var results = new List<T>();
while (await reader.ReadAsync(ct))
{
results.Add(map(reader));
}
return results;
}
private SqlCommand Create(
SqlConnection connection,
string sql,
CommandType type,
Action<SqlParameterCollection>? parameters)
{
ArgumentException.ThrowIfNullOrWhiteSpace(sql);
var command = new SqlCommand(sql, connection)
{
CommandType = type,
CommandTimeout = CommandTimeoutSeconds
};
parameters?.Invoke(command.Parameters);
return command;
}
}
How it works
Db wraps the connection factory from Recipe 1.1 and gives you three methods: execute a statement, read one value, read a list. Each opens a connection, runs one command and disposes everything before it returns. Parameters are added through a callback, which lets you use the typed extensions from Recipe 1.2 without any object[] in sight. Mapping is a function you pass in, so the helper never guesses at types.
The SqlHelper call above becomes:
// Usage snippet
List<string> names = await db.QueryAsync(
"SELECT Name FROM dbo.Region WHERE CountryCode = @Code;",
r => r.GetString(0),
p => p.AddVarChar("@Code", 2, code),
ct: ct);
int updated = await db.ExecuteAsync(
"dbo.Customer_Deactivate",
p => p.AddInt("@CustomerId", customerId),
CommandType.StoredProcedure,
ct);
That is the whole helper. I resist adding more to it. Every method you add is a method someone has to learn, and the things people usually want next (multiple result sets, output parameters, transactions) are clearer written directly against SqlCommand in the one place that needs them.
Variations and pitfalls
ScalarAsync<T>casts, it does not convert.(T)valueunboxes, so the C# type must match the SQL type exactly:intforINT,longforBIGINT,decimalforDECIMAL.COUNT(*)returnsINT;COUNT_BIG(*)returnsBIGINT. ForSCOPE_IDENTITY(), which returnsDECIMAL(38,0), read adecimalor cast in SQL.- Replacing SqlHelper gradually. You do not have to replace every call at once. Add
Dbalongside the old class, use it for new code, and convert old calls as you touch them. Search forSqlHelper.and the count should go down every sprint. - Why not a generic repository? A
Repository<T>that builds SQL from property names hides the SQL, which is the part you most need to see when tuning. If you want less hand mapping, use Dapper (next recipe) rather than writing your own ORM.
On .NET Framework
The class compiles on .NET Framework 4.7.2 and later if you replace the primary constructor with a normal constructor, use using blocks instead of await using on C# 7.3, and replace ArgumentException.ThrowIfNullOrWhiteSpace with an explicit check. The async methods on SqlCommand exist on 4.5 and later.