IC Improve Code Recipes

Chapter 1

Data Access Without the Boilerplate

Every business application I have worked on talks to SQL Server, and almost every one of them had its own way of doing it. Across my archive, 30 of the engagements contain hand-written data access or ADO.NET helper classes, 12,326 of them in total. The most common helper class name in the whole archive after Utility is SQLHelper, with 411 copies, and most of those are Microsoft's 2002 Data Access Application Block pasted into one project after another. Behind it come SQLUtility (278 copies), SQLManager (277), DataUtility (276) and DBManager (245). Each team wrote the same thing again, usually with the same bugs.

The bugs are predictable. Connections that leak when an exception skips the Close() call: of the roughly 7,098 files in the archive that create a connection with new SqlConnection(, only about 1,187 wrap it in a classic using statement, about 1 in 6. SQL built by gluing user input into strings, which shows up in about 8,353 files (1.9% of the hand-written C#) across 30 engagements. Readers mapped by column position, so a new column in a view quietly shifts every value one slot to the right. Transactions that commit half an order. Imports that insert 200,000 rows one round trip at a time and take an hour.

None of this needs a framework to fix. Modern ADO.NET with Microsoft.Data.SqlClient is small, fast and async from top to bottom. This chapter gives you the handful of pieces I now carry from project to project: a connection factory, typed parameters, a data helper of about a hundred lines, honest mapping code, transactions that either finish or roll back, bulk loading, and async streaming. Where Dapper is the better tool, I say so.

All C# listings use the NuGet package Microsoft.Data.SqlClient. The older System.Data.SqlClient still works on .NET Framework, but it only gets security fixes. New code should use the Microsoft.Data.SqlClient package. Recipe 1.4 also uses Dapper.

Recipes

  1. 1.1Open Late, Close EarlyConnections are pooled, but only if you give them back. A connection that is opened in a constructor, stored in a field, or closed only on the happy…
  2. 1.2Parameterized Queries, Typed ProperlySQL built by string concatenation is the oldest security hole in the business-application world, and it is still being written. Even teams that know…
  3. 1.3A Small Data Helper to Replace SqlHelperThe classic SqlHelper that many teams copied came from Microsoft's Data Access Application Block, released in 2002 for .NET Framework 1.0. It was…
  4. 1.4Mapping Readers to Objects, and When to Use DapperHand-written mapping is where silent data bugs live. Code that reads reader[3] breaks when someone adds a column to the view. Code that casts…
  5. 1.5Transactions That Commit or Roll BackAn order header and its lines must be saved together. Without a transaction, a failure after the header insert leaves an order with no lines. With a…
  6. 1.6Bulk Loads with SqlBulkCopy and Table-Valued ParametersA nightly import inserts a supplier's price file, 200,000 rows, one INSERT per row. Each insert is a network round trip and a log flush. The job that…
  7. 1.7Async Data Access All the Way DownData access is I/O, and a thread that waits for SQL Server is a thread that cannot serve another request. Most enterprise code I have inherited…

Chapter checklist

  • Search the codebase for SqlHelper, SQLUtility and friends. Add the Db helper and stop adding new calls to the old one.
  • Make every connection a using or await using declaration, opened as late and disposed as early as possible.
  • Replace string-built SQL with parameters, and replace AddWithValue with parameters typed and sized to match their columns.
  • Map readers by column name with typed getters, or use Dapper; delete DataSet code as you touch it.
  • Wrap multi-statement writes in one transaction with every command enlisted, and roll back in a catch that rethrows with throw;.
  • Move row-by-row imports to SqlBulkCopy into a staging table, and pass ID lists as table-valued parameters.
  • Make data access async from the controller to the reader, pass a CancellationToken through, and remove every .Result.
  • Move from System.Data.SqlClient to Microsoft.Data.SqlClient, and check your certificate setup for the new Encrypt=True default.