.T4 Templates in EF


Using .T4 Templates in EF

T4 stands for Text template transformation toolkit, a template-based code generation engine built into Visual Studio. It is available in Visual Studio from Visual Studio 2008 and a higher version of Visual Studio. T4 engine allows you to generate C#, T-SQL, XML or any other text files using ASP.NET – ASPX template like syntax. T4 template has .tt extension.

T4 templates with Entity framework

T4 templates in the entity framework generate C# or VB entity classes from EDMX files. Visual Studio 2013 or 2012 provides two templates- EntityObject Generator and DBContext Generator for creating C# or VB entity classes. The additional templates are also available for download.

To use one of these templates, right-click on the design surface of a .edmx file and select the "Add Code Generation Item" command. Selecting the command will launch a dialogue box, allowing you to choose one of the installed code-generation items or search for new items online. The chosen template will generate the C# or VB code files, i.e. entity and context classes.

What is the importance of T4 in the Entity framework?

T4 files are heart in EF code generation. So the T4 code templates read the EDMX XML file and generate C# behind the code. This C# behind code is nothing but your entity and context classes.

If you create a project using VS 2012, you will see the following hierarchy. At the top, we have the EDMX file, followed by the TT or T4 file and then the.CS code file.