Generate NHibernate Mappings from your SQL Server or MySQL database
My favorite tool when working with NHibernate is MyGeneration. MyGeneration is a code generator and O/R mapping solution. It’s as simple as selecting the script to run, setting up your database connection string, and clicking run. It can instantly generate class files along with the required NHibernate mapping files. This can save a lot of time upfront when you need to quickly access your database.
Here is my step-by-step guide to getting NHibernate mappings and class files from your database:
1) Download and install the latest copy of MyGeneration from here.
2) Make sure you have the required connector for your database. Several databases are supported natively; however, others will require an additional download. See this page for more information and links to connectors to download. Note: My computer has Visual Studio 2005 and SQL Server 2005 installed, so the SQL Server connectors were already installed. However, I did need to install a connector for MySQL. Once installed, I also had to navigate to the installation folder to retrieve the binary connector file. It was called MySql.Data.dll. I simply copied this into the base MyGeneration folder and was ready to go!
3) Run MyGeneration. When prompted to set the Default Settings, set the connection to your database. For MySQL select MySQL2 from the driver list. Remember to test the connection to make sure it works before saving.
4) Find the template for NHibernate. On the left hand side of the screen is the Object Browser. Click the globe icon to open the Online Template Gallery. Expand the NHibernate section and choose a template. In my case, I picked one for NHibernate 1.2. Press the save icon to save it locally.
5) Expand the NHibernate folder in the Object Browser. Double click on a template to open it. Click the green start button to run. The pop up window will allow you to specify various options for the output. Typically, you are able to specify the namespace and assembly information, select a database using your connection information, and which tables/views to map. One mistake I made at fist was not selecting any tables. If you do not select any, it will still say the script ran successfully. When you are happy with your selections, choose OK to run the template. The code will be created in your output folder!
As you can see, once setup, code generation can quickly speed up the development process by eliminating the tedious tasks and letting developers focus on what is really important - the business logic!
Posted in Development | No Comments »