Using T4 Templates to generate EF classes
Spurred on both by the success of Damien Guard in using T4 to generate Linq to SQL code and of Jeff Reed from the EF team who built a prototype for using T4 to generate EF code, I recently hacked something up that makes it fairly easy to use T4 to generate EF classes. This is an early draft--there are a number of "to do" items--but hopefully someone will find it useful.
In order to try it out, all you need to do is:
- Download the template and extract it from this zip file.
- Add it to your solution and give it the same name as your EDMX file (except with .tt extension rather than .edmx).
- Set the Build Action on the .designer.cs file to None (since you will now use the code generated by the T4 template rather than what is generated by the EDM designer).
The output now is mostly the same as what the shipping codegen creates except that:
- I don't have a VB version yet. Sorry VB fans. This goes on the to-do list, and it really shouldn't be that hard.
- I added a bunch of using statements at the top of the file so that the code throughout the file can be shorter and easier to read--this means that if you have a model with an entity type whose name conflicts with a type in one of the included namespaces, then you will get a compiler error--you could always modify the template to fully qualify things instead.
- I added a series of #region directives so that you can nicely collapse things and navigate the generated code.
- There are a few things that I haven't implemented yet (see to do comments at top of the template).
Already, though, it's nicer to look at, and if you would like to customize the output, this is a much more pleasant starting point than codegen events with the existing code-dom based generator.
Let me know what you think.