skip to the main content area of this page
Patterns and Practices

 

Sample Fluent NHibernate T4 Templates for Code Generation via LINQ To SQL


I had a small web application that I was building using LINQ To SQL as the O/R Mapper and thought I would switch it out with NHibernate and Fluent NHibernate. Given I had a LINQ To SQL DBML that already had the various entities and relationships I thought I would try to use that metadata to generate the Fluent NHibernate Mapping Classes using T4 Templates as opposed to manually creating the classes by hand.

 

Based on LINQ To SQL T4 Templates

I knew Damien Guard had already put together a nice set of T4 Templates that generate LINQ To SQL Classes which I use often, so I thought I would steal all of Damien's hard work to create T4 Templates for Fluent NHibernate :) Much thanks to Damien for providing those templates as they provided exactly what I needed to generate Fluent NHibernate Mappings.

The solution is below for a test database:

 

T4 Templates - Fluent NHibernate

 

The NHibernateMapping.tt template must be suffixed with the name of the LINQ To SQL DBML file. Using a Test.DBML file the template gets named to NHibernateMappingTest.tt.

Notice the L2ST4.ttinclude file which is compliments of Damien Guard's LINQ To SQL Templates. I have included it, but I recommend you always check to see if he has released an updated version on his website.

 

Fluent NHibernate

Fluent NHibernate allows one to map domain entities ( classes ) to database tables without using NHibernate XML. This is an evolving project still in alpha. The templates may go out-of-date as the project evolves. The templates are a proof of concept that I used to jumpstart my switch from LINQ To SQL to NHibernate. Using the LINQ To SQL Metadata it generates something like:

 

T4 Templates - Fluent NHibernate

 

If you can, I would try to take advantage of Fluent NHibernate's AutoPersitenceModel to avoid the mapping classes if possible.

There are known limitations in the ReadMe.txt file and probably other limitations that I am not aware of. You can change the templates to your liking, which is what I expected when I made them available for download. The templates were put together rather quickly for use only once in my particular situation. That being said, they saved me a lot of work :)

 

Conclusion

T4 Templates are a nice addition to Visual Studio 2008 for code generation. You can find T4 Templates in many cool projects like Sharp Architecture, SubSonic 3.0, etc. You can watch a screencast on T4 Templates as well as read T4 Template Tutorials.

Download the Fluent NHibernate T4 Templates here.

Other Code Generation Tools.

 

Related Posts:


Tags: CodeGeneration, NHibernate, ORMapper, T4


Topics



 

Popular Tags



Recent Links