Creating Dapper models

Dapper needs a C# model of the corresponding SQL table for it to work most effectively.

For example, for this SQL table:

Figure 1. SQL CREATE TABLE for Song table.

It needs a class like this:

Figure 2. C# model for Song table (for Dapper, for example)

Generating SQL Server table schema

Creating models by hand gets old very quickly. To solve this problem GenerateJsonTableSchema (at this repo) generates a Json schema of all of the tables and views in a SQL Server database.

GenerateJsonTableSchema creates this Json schema for the Song table above:

Figure 3. Json schema for Songs table.

What can you do with the Json schema?

This Json schema file is intended to be used with a templating engine to create C# models and other code for the corresponding table. The schema file schema includes column-level details for each column and then several special-case table-level values.

For example, Librettox (which is a Python program that uses the Jinja2 templating engine), the Json schema from figure 3, and this template:

Figure 4a. A Lilbrettox template to create a CS model.

produces this output:

Figure 4b. The output from Figure 4a.

Leave a Comment

Your email address will not be published. Required fields are marked *