Keep SQL Out of Your Forms: A Three-Layer Rule for WinForms Apps
Open an old WinForms business app and you'll often find SQL written straight into the button click handlers. There's a SqlCommand with a long SQL string, wrapped in a try/catch that shows ex.Message as it is. The connection string was copy-pasted from the form next door. It all works fine right after you write it. The trouble comes later, when you only want to rename one column and end up going through every screen that uses it.
This article is about one rule: don't write SQL in forms. You don't need a framework or an ORM for it. The idea comes from Delphi's TDataModule. I brought it over to WinForms as it is, and that's what I use.
The rule in one picture
There are three projects.
Screens ──► Data ──► Common
(forms) (SQL) (helpers)
- References point one way. Screens references Data and Common. Data references Common. Common references nothing. No project references Screens.
- SQL is written only in Data. Not in forms, not in Common, not in a "Utils" class.
- Common has no SQL and no UI. A helper that needs a
SqlConnectionor aControldoesn't go into Common.
That's all there is to the design. The compiler enforces line 1 for you, because project references can't be circular. Nothing enforces lines 2 and 3, so the people who write the code have to keep them. That's why I've shaped the sample below so that keeping them takes as little effort as I could manage.
Here's how it maps to Delphi.
| Delphi | This article, in WinForms |
|---|---|
TDataModule, a non-visual container for queries |
A class derived from DataModuleBase (a Component) |
| The form owns the data module and frees it with itself | The form adds it to its components container; disposing the form disposes it |
| SQL goes into queries on the data module, not into the form | SQL goes into data modules in the Data project, nowhere else |
Why not a repository, EF, or MVVM?
Those are all sound designs. But when you have to add one later to an existing business app that a small team maintains, it's often too big, to be honest. So I kept the three-layer rule small on purpose.
I don't use an ORM, because ADO.NET and DataTable are enough for filling grids. There are no presenters or view models either, so a form stays a form and just stops running SQL. Where you might expect a DI container, there's one static factory that decides which implementation a screen gets.
If you need EF or a service layer later, you can add it inside Data and the screens don't have to change. That's what the one-way references are for.
A data module
A data module is a class that only runs the SQL of one business area. It derives from Component so that a form can put it into its components container, and then it's disposed together with the form. It's the same ownership as a Delphi TDataModule owned by its form.
public abstract class DataModuleBase : Component
{
private readonly string _connectionString;
protected DataModuleBase(string connectionString)
{
_connectionString = connectionString;
}
/// Runs a SELECT and returns the rows as a DataTable (ready for grid binding).
protected DataTable Query(string sql, params SqlParameter[] parameters)
{
using (var connection = new SqlConnection(_connectionString))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.AddRange(parameters);
connection.Open();
var table = new DataTable();
using (var reader = command.ExecuteReader())
{
table.Load(reader);
}
return table;
}
}
protected static SqlParameter P(string name, object value)
{
return new SqlParameter(name, value ?? DBNull.Value);
}
}
This code makes two decisions.
The first is that no connection stays open. Each call opens the connection, runs the command and closes it. Opening it every time may look wasteful, but ADO.NET connection pooling keeps the cost low. And since the screens never hold a connection, a screen can't forget to close one. Calling Open on a connection that's already open throws an exception, and that can't happen either when every call opens a new one. In code that does keep a connection, I often use a ReOpen method (cn.Close(); cn.Open();), because it works whether the connection is open or closed. But a Close in the middle of a transaction ends that transaction (it's rolled back) and closes any open reader.
The second is that the base class returns a DataTable and never a reader. A reader keeps its connection open for as long as it's being read, so if you hand one to a form, the form ends up holding a connection.
One module per business area, not per table
public sealed class CustomerDataModule : DataModuleBase, ICustomerData
{
public CustomerDataModule(string connectionString) : base(connectionString) { }
public DataTable Search(string text)
{
const string sql = @"
SELECT Id, Code, Name, Email
FROM dbo.Customers
WHERE @text = ''
OR Name LIKE '%' + @text + '%'
OR Code LIKE @text + '%'
ORDER BY Name;";
return Query(sql, P("@text", (text ?? "").Trim()));
}
}
All the SQL about customers is in this file. When a column changes, this is the file you open. If the search needs a join to categories later, the screen doesn't change, because all the screen knows is this: search by text, get back a table with these columns.
I split modules by what the user does (customers, orders, month-end closing), not by table. That way a screen usually uses one module, while a module usually touches several tables.
The interface and the fake
The screen doesn't use CustomerDataModule directly. It uses an interface:
public interface ICustomerData
{
/// Columns: Id, Code, Name, Email.
DataTable Search(string text);
}
The interface has no SqlConnection and no SqlDataReader in it, and no connection string or SQL text either. That's why the Screens project doesn't need System.Data.SqlClient.
And once there's an interface, you can add a second implementation that needs no database:
public sealed class CustomerDataFake : ICustomerData
{
private readonly DataTable _rows = BuildRows(); // a few invented customers
public DataTable Search(string text)
{
text = (text ?? "").Trim().Replace("'", "''");
var filter = text.Length == 0
? ""
: "Name LIKE '%" + text + "%' OR Code LIKE '" + text + "%'";
using (var view = new DataView(_rows, filter, "Name", DataViewRowState.CurrentRows))
{
return view.ToTable();
}
}
}
"Fake" sounds like something for tests, but it gets used in everyday work too. You can demo the app on a PC that can't reach the database, and a new developer can run the screens before setting up a database. It also helps more than you'd expect when you've only changed a layout and want to check it without touching production data. The screen code is exactly the same with either implementation.
The screen
public sealed class CustomerListForm : Form
{
private readonly IContainer components = new Container();
private readonly ICustomerData _customers;
public CustomerListForm(AppSettings settings)
{
InitializeComponent();
// The form owns the module. Dispose(form) => Dispose(module).
_customers = DataModules.CreateCustomerData(settings, components);
}
private void Reload()
{
var table = _customers.Search(_searchText.Text);
_grid.DataSource = table;
_status.Text = table.Rows.Count + " customer(s)";
}
}
DataModules.CreateCustomerData is a static factory in the Data project. It reads Provider=Fake or Provider=SqlServer from app.ini and creates the matching implementation. If that implementation is a Component, the factory also adds it to the form's container. A screen never writes new CustomerDataModule(...), because once it does, that screen can't be switched to the fake anymore.
What you get
First, changing a column gets easier. You open one file, and you search the Data project instead of the whole solution. Then there's the database: change one line in app.ini and the UI runs without one.
The rule is short, so it's also easy to explain to a new developer. "Forms call modules, modules run SQL" covers it. As for the direction of the references, the compiler checks that. If Data tried to reference Screens, the reference would be circular and the build would fail.
Two pitfalls
The first is that Common turns into a dumping ground. Once someone puts a "handy" ExecuteQuery(string sql) helper into Common, every form can run SQL through Common, and the rule doesn't mean anything anymore. I use two questions to decide whether something belongs in Common: does it need a database type, and does it need a control? If either answer is yes, it stays out of Common.
The second is showing raw exception messages to the user. SqlException.Message just isn't written for users. In the lite sample the form shows ex.Message as it is, but that's because the sample is about structure, not error handling. In a real app the data layer translates it. A unique-key violation becomes "A record with the same code already exists", and a deadlock becomes "The database was busy, please try again". With that in place, the screens catch one exception type and don't need to look at error numbers.
Where to go from here
The lite sample (three projects, one screen, fake and SQL Server providers, builds with dotnet build, no NuGet packages) is on GitHub: https://github.com/purupurusystems/winforms-three-layer
If you maintain a WinForms app with SQL in its forms, I'd start with one screen and move its SQL into one module. You don't have to convert every screen at once. Each screen you move is one more screen where a column change means changing one file.