SQL tip: generating C# directly from SQL
Hand-coding C# properties for every table is one of those tasks that's equal parts repetitive and error-prone. Typos, missed columns, or duplicating work every time the schema changes can quickly get messy.
With a bit of SQL, you can generate fully-formed C# property definitions straight from your database schema. That means your models always reflect your tables, and repetitive boilerplate work disappears.
We'll walk through this process, using SQL’s CONCAT function with metadata tables to dynamically produce C# code. With this pattern you can scaffold DTOs and C# objects, DataTable creation logic, row-to-object mapppers, parameter signatures for stored procedures and bindings for Dapper or gRPC objects.
A simple (but powerful) example
Let's say you have a table called stage_GREG_20_EntityMaster. You want to build a C# object class or DTO matching its structure.
Here's a SQL query that inspects the columns and dynamically generates the C# property declarations you need:
What this does:
Looks up every column in
stage_GREG_20_EntityMasterMaps the SQL type to the closest C# type (nullability included)
Generates the property line in standard C# format, eg:
Now you can copy-paste this straight into a C# class file:
Change the table name or tweak the mapping, and it's ready to generate code for any model in your database.
Extending the Pattern
This core approach can be adapted for:
Building
DataTablecreation logicGenerating row-to-object or object-to-row mappings
Parameter signatures for stored procs
Mapping between objects and gRPC protocol buffers
Just adjust the CONCAT output to generate the lines of code you need.
Summary
Generating code directly from SQL flips the usual process on its head: instead of chasing schema changes in C#, you let the database define the source of truth and generate your models automatically.
It’s simple, adaptable, and one of those quiet productivity boosters that pays off every time your schema evolves.