VS T4 Templates – Working Well and Saving Time

In a previous post, I mentioned the T4 text template feature that is built in to Visual Studio. This past week, I used T4 templates on one of my projects and it turned out very well. I created the templates to help automate the creation of the classes in our DAL layer.

The templates provided us with a couple of nice benefits:

  1. Saved time – reduced the time to create the DAL by 50 – 75%.
  2. Consistency – the classes are implemented in a consistent pattern, while allowing for some constrained customization as needed.
  3. Updates – allows us to update the implementation of all the dal classes by changing the template and re-saving the dals.

The implementation had a couple nice features that worked out well:

  1. The body of the template is in a single file. Each dal uses an include directive to pull it in to each dal. This prevented multiple instances of the T4 template code and allowed us to easily modify the template for all dals.
  2. Each dal’s template has a parameter section that allows us customize the template. This section lets us do a couple things:
    1. Exclude fields from the dal.
    2. Map DB fields to entity fields if they have different names.
    3. Modify the types of the fields to allow conversion / casting between the entity and the database.
  3. The templates use the System.Data.SqlClient.SqlConnection’s GetSchema() method to get the database schema. This provides a simple and powerful way to get the structure of the database.

I’m happy to say that the team likes using the templates and is looking forward to using them in future projects.


One thought on “VS T4 Templates – Working Well and Saving Time

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: