Using NHibernate with Visual Studio .NET

This page is a collection of tips and tricks for using NHibernate with Visual Studio .NET. Unless indicated otherwise, these tips relate to VS.NET 2003, but may work with other versions. The NHibernate Quick Start Guide has more general information about getting started with NHibernate.

Integrating Help into Visual Studio .NET

The NH reference documentation and the NH and NHC SDK documentation can be integrated with the Visual Studio .NET help system. The necessary files are included in the distribution zip files. To install them you should take the following steps:

  • Download the NHibernate and NHibernateContrib distribution zip files
  • Unzip these files to suitable locations (e.g. C:\NHibernate\ and C:\NHibernateContrib).
  • Download and install H2Reg from HelpWare.
  • Copy H2Reg.exe and H2Reg.ini from the H2Reg installation folder (typically C:\Program Files\HelpWare\H2Reg) to the NHibernate\doc folder.
  • From the NHibernate\doc\en\Help2 folder, execute the command h2reg -r CmdFile=NHibernateCollection.ini.
  • From the NHibernateContrib\doc\sdk folder, execute the command h2reg -r CmdFile=NHibernateContrib.ini.
  • To unregister the collections, substitute -r with -u in the above commands.

Setting Up IntelliSense for NHibernate Mapping Files

If you copy nhibernate-mapping-2.0.xsd and nhibernate-configuration-2.0.xsd from the install location to C:\Program Files\Microsoft Visual Studio .NET 2003\Common7\Packages\schemas\xml (or wherever VS.NET is installed), you will get IntelliSense and validation in the VS.NET XML editor when editing NHibernate mapping and configuration files. In VS.NET 2005 (beta 2) the directory is C:\Program Files\Microsoft Visual Studio 8\Xml\Schemas.

Using NHibernate in a VS.NET Project

Use the Add New Item wizard to add an XML file to your project. It is recommended that you create a mapping file for each class, named <classname>=.hbm.xml= in the same directory as the class file. So, if you class file is called MyClass.cs or MyClass.vb, the mapping file will be MyClass.hbm.xml.

On the file properties for the mapping file, set Build Action to Embedded Resource. This will build the file into the assembly as a resource, and it is required if you want it to be accessed by the NHibernate Configuration object's AddAssembly method.

Also, some people like to arrange their mapping files in a folder named Mappings (or something similar) in the project.

Click in the editor for the mapping file, and in the properties window, expand the drop-down list for the targetSchema property and select urn:nhibernate-mapping-2.0. This will create the root <hibernate-mapping> node and set the xmlns attribute. If you don't see the urn:nhibernate-mapping-2.0 option in the drop-down, you need to copy the nhibernate-mapping-2.0.xsd file as detailed above.

Having set the xmlns, you will get IntelliSense in the editor for elements and attributes, and highlighting of any invalid XML.