I am a lazy developer, so I am always looking for tools that help me to automate my code generation. Needless to say, Data Access Layer (DAL) easily the most tedious code to write, regardless of whether( or especially when) you have ORM to help you.
Currently I am using CodeSmith to help me in my NHibernate DAL generation. NHibernate is a popular ORM for .Net, and it's open source. CodeSmith is a known name in code generation. So I guess going by these two tools would solve all my needs... apparently no, yet.
You can't generate the NHibernate DAL in one touch if you are querying across multiple databases using CodeSmith tool; you have to do some manual adjustment to the code before the DAL works. So this is a post explaining how to make NHibernate work with multiple databases using CodeSmith.
I am assuming that you are accessing two different databases in the same server, if you want to access different databases in different servers than you might need to find your own help.
- Create a CodeSmith project (*.csp), choose the correct master template, then set the SourceDatabase name to a database, let's call it mystore.
- For all the options, you can set them to anything you want. The most important thing is BaseNamespace must be the same for both of the databases. In this case, we set the BaseNamespace to be CodeSmithJoin.Generated.Base.
- Click OK
- Generate the DAL by right-clicking on csp file and Choose Generate Outputs.
- Copy the content of ManagerFactory.cs to clipboard, or a file, you will need it later.
- Now you are done with the MyStore database code generation. Let's try to generate the DAL for MyStore2.
- Create another CodeSmith project, set the SourceDatabase to mystore2. Set the BaseNamespace to be CodeSmithJoin.Generated.Base. To avoid confusion, choose other namespaces for BusinessNamespace, ManagerNamespace and UnitTestNamespace. I choose MyStore.Generated.* for this purpose.
- Click OK.
- Examine the *.hbm.xml from MyStore2, manually add a schema property to the hibernate-mapping tag, set the schema to be "MyStore2". Maybe CodeSmith template can improve on this.
- Create a ManagerFactory1.cs, paste the result in step 5 into it. And don't forget to put partial tag on both the IManagerFactory and ManagerFactory on both the ManagerFactory.cs and ManagerFactory1.cs. This is required because the ManagerFactory class is now splitted into two parts, one in ManagerFactory1.cs, and another in ManagerFactory.cs. Maybe CodeSmith template can improve on this as well.
- Create a hibernate.cfg.xml, add to your project, and now you can access two databases!
Here's how you can get NHibernate to work with multiple databases, using CodeSmith. And sure, I hope that CodeSmith can incorporate all the above suggestion so that code generation can be made easier, so that we the developers have more time browsing reddit.