IC Improve Code Recipes

Recipe 17.1 · C#

Replacing String-Built Queries in SQLManager

Problem

SQLManager has one public method for nearly every query the product runs: GetIncidentFromID, GetDrillFromID, GetAudit, GetAuditRBPS1 through GetAuditRBPS18, and more than 300 others. Most build a SQL string with string.Format, hand it to a generic GetData, and return an untyped DataSet. Mapping to a model happens later, in SQLUtility, with column names typed a second time.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

This is from CFATS Manager, abridged and re-wrapped. The column list is shortened.

C#
// From CFATS Manager: CFATSLibrary\Data\SQLServer\SQLManager.cs
// lines 246-267 and 1587-1595 (abridged, re-wrapped)
public DataSet GetIncidentFromID(int IncidentID)
{
    string SQL = string.Empty;
    SQL = "select FacilityID,IncidentID,IncidentTypeNo, ... "
        + "FileGUID from vwFacilityIncidentView "
        + "where IncidentID = {0}";

    string Query = string.Format(SQL, IncidentID);
    DataSet dsData = GetData(Query);
    return dsData;
}

public DataSet GetData(string SQL)
{
    SqlConnection DBConnection = null;
    DataSet DS = new DataSet();
    try
    {
        DBConnection = GetConnection(_ConnectionString);
        string Query = SetQuery(SQL);
        DS = SQLHelper.ExecuteDataset(DBConnection,
            CommandType.Text, Query);
    }
    catch (Exception ex)
    {
        HandleException(ex, "Get data failed");
    }
    finally
    {
        DisposeConnection(DBConnection);
    }
    return DS;
}

With an int parameter this particular query can't be injected. The habit is the problem. The same pattern is used with string parameters all through the class, including for lookups by name, and GetData accepts any string at all. When the query fails, HandleException records the error in the manager's State and returns an empty DataSet. The caller has to remember to look.

The improved recipe

Packages: Microsoft.Data.SqlClient (6.x).

C#
using System;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;

namespace ImproveCode.Cfats.Data;

public sealed record IncidentRecord(
    int IncidentId,
    int FacilityId,
    string IncidentType,
    string Name,
    DateTime OccurredOn,
    string? Location,
    string? ReportedTo,
    string? Description,
    Guid? FileId);

public interface ISqlConnectionFactory
{
    SqlConnection Create();
}

public sealed class SqlConnectionFactory(string connectionString)
    : ISqlConnectionFactory
{
    public SqlConnection Create() => new(connectionString);
}

public sealed class IncidentRepository(ISqlConnectionFactory db)
{
    private const string SelectById = """
        SELECT IncidentID, FacilityID, IncidentTypeName,
               IncidentName, OccurenceDate, Location,
               ReportedToPersonName, Description, FileGUID
        FROM dbo.vwFacilityIncidentView
        WHERE IncidentID = @IncidentId;
        """;

    public async Task<IncidentRecord?> GetByIdAsync(
        int incidentId, CancellationToken ct = default)
    {
        await using SqlConnection conn = db.Create();
        await using SqlCommand cmd = new(SelectById, conn);
        cmd.Parameters.Add("@IncidentId", SqlDbType.Int).Value =
            incidentId;

        await conn.OpenAsync(ct);
        await using SqlDataReader reader = await cmd
            .ExecuteReaderAsync(CommandBehavior.SingleRow, ct);

        return await reader.ReadAsync(ct) ? Map(reader) : null;
    }

    private static IncidentRecord Map(SqlDataReader r) => new(
        IncidentId: r.GetInt32(0),
        FacilityId: r.GetInt32(1),
        IncidentType: r.GetString(2),
        Name: r.GetString(3),
        OccurredOn: r.GetDateTime(4),
        Location: r.IsDBNull(5) ? null : r.GetString(5),
        ReportedTo: r.IsDBNull(6) ? null : r.GetString(6),
        Description: r.IsDBNull(7) ? null : r.GetString(7),
        FileId: r.IsDBNull(8) ? null : r.GetGuid(8));
}

How it works

The query and its mapping live side by side in one small class per aggregate, instead of the query in SQLManager and the mapping in SQLUtility, 2,000 lines apart. The SQL is a raw string literal with a named parameter. The value travels separately, typed as SqlDbType.Int, so there is no string to inject into, and SQL Server can reuse one plan for every ID.

await using closes and disposes the connection, the command and the reader on every path. The original needed a finally block and a PersistConnection flag to do the same. Connection pooling already gives you cheap connections, so there is nothing to gain by holding one open.

The method returns IncidentRecord?. A missing row is null, which the compiler forces the caller to handle. A failed query throws SqlException and goes up to whatever handles errors for the request. It does not vanish into a state object. The record's nullable members match the nullable columns, so a reader can tell from the type alone which values may be missing.

ISqlConnectionFactory is the only seam. In a test you point it at a LocalDB or container database. The original read ServerInfo.GetConnectionString(), a static call to ConfigurationManager, inside every Usage method, which made that impossible.

Variations and pitfalls

  • Dapper. If you have dozens of these, Dapper removes the mapper: conn.QuerySingleOrDefaultAsync<IncidentRecord>(sql, new { IncidentId = id }). Alias the columns to match the record's property names. Chapter 1 compares the two.
  • Don't keep the one-method-per-query god class. Splitting SQLManager by aggregate (incidents, drills, audits) is what makes the change reviewable. Move one aggregate at a time and delete the old methods as callers move.
  • Watch the old null handling. The legacy mappers turned NULL into something else. This one is from CFATS Manager, SQLUtility.cs lines 212-217, re-wrapped:
C#
public static DateTime GetDateValue(object DBObject)
{
    DateTime DateValue;
    DateValue = (DBObject == System.DBNull.Value)
        ? DateTime.Now : (DateTime)DBObject;
    return DateValue;
}

A missing date became now. Other overloads used a sentinel of 1/1/1901 (Constants.NO_DATE). When you port a screen, check which one it relied on. Use DateTime? and decide at the UI what "no date" should look like.

  • Views are still fine. The product reads through views such as vwFacilityIncidentView. Keep them. They are a stable contract between the schema and the code, and they let you rename columns without a release.