Sneak Peek – Using Code Generation Templates with the Entity Framework 4.0

 


The information in this post is out of date.

Visit msdn.com/data/ef for the latest information on current and past releases of EF.


 

In the first version of the Entity Framework code generation was implemented internally using CodeDom. The Entity Framework APIs provided some hooks for customizing the generation, but customizing was tricky, relatively inflexible and wasn’t integrated into Visual Studio.

In .NET 4.0 all these limitations go away.

The Entity Framework now leverages T4, Text Template Transformation Toolkit, which makes customizing Code Generation easy, flexible and powerful, and the experience is also fully integrated into Visual Studio.

T4 itself is very simple, in fact you can try it out in Visual Studio 2008 today if you want. T4 provides a clean way of interleaving control logic and references to variables with output text, that is reminiscent of the techniques used widely in web server programming (for those familiar with old-school ASP or ASP.NET MVC views it will look vaguely familiar).

Out of the box the Entity Framework will ship with two T4 templates, both of which will produce EntityObject derived Entities. One in VB that produces VB code, and one in C# that produces, yes you guessed it, C# code.

So how does it all work?

Well if you are happy with our default code-gen, you don’t do anything, and your generated code lives under the EDMX file as before. i.e:

 

If however you want to customize the code, you add a new turn T4 template into your VS project, by right clicking on the EDMX designer canvas, and selecting “Add New Artifact Generation Item…” from the context menu.
This will show a screen where you can select one of the registered templates:

 

 

Once you’ve added one to your project the generated code no longer resides under the [model] .edmx file it will reside under the [model] .tt file instead:

 

 

Now to customize you Entities you simply modify the tt template file. Every time you save changes to the template, the dependent code is regenerated automatically.

It is that simple.

Overtime we plan to ship more templates, for example to produce POCO Entities or Self Tracking Entities.

Stay tuned for a more in depth discussion of our Code Generation enhancements soon.

In the meantime check out the MSDN documentation for more information.

Cheers,

Alex James
Program Manager, Entity Framework