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:
- Saved time – reduced the time to create the DAL by 50 – 75%.
- Consistency – the classes are implemented in a consistent pattern, while allowing for some constrained customization as needed.
- 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:
- 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.
- Each dal’s template has a parameter section that allows us customize the template. This section lets us do a couple things:
- Exclude fields from the dal.
- Map DB fields to entity fields if they have different names.
- Modify the types of the fields to allow conversion / casting between the entity and the database.
- 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.