Text Template Transformation Toolkit (T4 Templates) and Entity Framework


A Text Template Transformation Toolkit (T4) template is a general purpose template engine; using T4 we can generate C#, VB code, XML, HTML or text of any kind. The code generation is used in Visual Studio in technologies like MVC, Entity Framework, LINQ to SQL and many other that use those templates. The Entity Framework supports extension or manipulation of the code generation using the T4 template. In short a T4 text template is a mixture of text blocks and control logic that can be generated into a text file. The control logic is written as fragments of C# or VB program code.

T4 Templates in Entity Framework

In Entity Framework, we can use T4 Templates to extend and manipulate code generation. In the following example I have added a simple entity model within a console application.


Now to add a T4 Template for our entity model. We have two ways to add the T4 Template for our entity model; they are:

  1. Right-click on the entity model and select "Add Code Generator Item".



    Select "ADO.net Entity Object Generator" from the "Add new Item" dialog and click on the "Add" button. At this time a security warning dialog is shown to ask if  you trust the source that generated the T$ template.


  2. You may also add a T4 template by right-clicking the project then select "Add new item" then select "ADO.net Entity Object Generator".


This will also show a security warning described as above.

The only difference is that in this second case you must replace the entity model name manually in the model.tt file as shown below. And you must also delete the code in model.designer.cs manually.


Now all our code is within; our new T4 template file has the extension .tt.


T4 templates enable us to implement code generation. A T4 template is very useful in a large and complicated model. With the T4 template, if we change the table name in a database, we don't need to find and change the name of the corresponding C# class. Instead of this, we can re-execute the template and regenerate the class definitions; just open the model.tt file then save it, it will automatically generate new code for us. We can also force a template transformation by right-clicking on a template and selecting "Run Custom Tool". It is also the flexibility of the customization and total control.

How to use Sample

To run the sample, you must change the connection string that points to the testing database. And the project also contains the database table script.