T4 Templates in Entity Framework 4
T4 templates or
Transformation Toolkit is
a mean of creating a code
generation artifacts which
can save a lot of time.
This technology is a part of
Visual Studio since 2005 but
was one of those technologies
that were kept in secret by Microsoft.
Almost all the code generation stuff that is being used
in Visual Studio in technologies such as MVC, Entity Framework,
LINQ to SQL and many other use those templates as backbone
to generate code. In this post I’m going to show one of the
new features of EF4 which is the use of T4 templates to extend
or manipulate the code generation. If you like to read more about
T4 templates I recommend Scott Hanselman’s post –
T4 (Text Template Transformation Toolkit) Code Generation –
Best Kept Visual Studio Secret which has many references to good
T4 Templates in Entity Framework 4 Example
In EF4 we can use T4 templates to extend and manipulate the
code generation. In the example I start with a very simple
console application. That application has a Entity Data Model
which is the same School model that I used for all my previous
Adding a T4 Template
Now lets explore the process of using the T4 templates.
In order to use the T4 templates, from the Entity Framework
Designer surface use the right mouse button to open the menu
and choose the Add Code Generation Item menu item:
This will open the Add New Item window that holds only EF4 T4
As you can see I have two T4 templates that I can generate. I choose the
ADO.NET EntityObject Generator. A security warning will be popping up to
check if you trust the source that generated the T4.
I choose to continue and a new file with the extension .tt is added to
When you observe the generated .tt file you can see that all the generated
stuff of EF is located in a new .cs file that is attached to it. When opening
the SchoolModel.Designer.cs file that is attached to the edmx file you will
see a comment that say it is no longer being used:
Now that we have our own code generation file we can start manipulating
the generated code.
Manipulating Generated Code Using a T4 Template
Say for example that I want to remove the generated OnContextCreated
method which is called from the ObjectContext’s constructors:
Opening the .tt file and then removing the OnContextCreated
method call from the constructors and also the generation of the
OnContextCreated partial method will result in the following
Of course this is silly to do because this is an extension point
when the context is being created but for the example it is enough
to show the power of the T4 templates.
The T4 templates enables us to implement code generation.
When you have something that you do manually more then one time
then applying a T4 template can help you to make it automatic.
As I show in the post, EF4 is shipping with a way to manipulate the
code generation using T4 templates. Next time when something bother
you in the EF generated code you can do something about it.