The NHibernate Designer is a great way to design data models for use with the NHibernate object-relational mapper. But once you’ve captured your data model, you may be interested in generating other code from it — anything from data transfer objects (DTOs) right through to scaffolding for a simple admin site. In some cases you can do this by editing the designer’s NVelocity templates, but sometimes you want to generate content that doesn’t fit in a C# or VB file, or maybe you just don’t like NVelocity. (I can sympathise with that.) Fortunately, you can use Visual Studio’s standard T4 templating system to do your own code generation off a NHibernate model. Let’s dive in!
Creating the template
To create a T4 template, add a new item to your project and choose Text Template. This gives you an empty starter T4 file.
Next, you need to hook the template up to the NHibernate Designer DLLs. You do this in two parts. First, you add the following incantation to the template directive:
<#@ template inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" ... #>
Don’t worry about what this means — it’s just a bit of plumbing to bring in the same Visual Studio subsystem that the NHibernate Designer sits over. Next, you add a couple of assembly references:
<#@ assembly name="Mindscape.NHibernateModelDesigner.DataModel.dll" #>
<#@ assembly name="Mindscape.NHibernateModelDesigner.Dsl.Mapping.dll" #>
Also, by default the T4 template generates an output file with a .txt extension. I’m going to stick with this to keep the example simple, but more usually, you’ll want something more meaningful such as .cs or .aspx. If so, change the output directive:
<#@ output extension=".cs" #>
Finally, you need to hook your template up to your NHibernate model, using a NHibernateModel directive. I’m going to assume we have a file called StoreModel.nhmodel, so my directive looks like this:
<#@ NHibernateModel processor="NHibernateModelDirectiveProcessor"
Now everything is ready, we can start to generate some code.
Read more: Mindscape blog