As we saw in Chapter 1, ConfORM uses conventions to build HbmMapping objects that can be added directly to the NHibernate configuration. In this recipe, I'll show you how to add ConfORM mappings to our NHibernate configuration.
ConfigWithConfORM
.ConfigWithConfORM
project, add references to NHibernate.dll
and NHibernate.ByteCode.Castle.dll
in the Lib
folder.ConfigWithConfORM
, add a reference to the Eg.ConfORMMappings
project.App.config
with the following configuration:<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/> </configSections> <connectionStrings> <add name="db" connectionString="Server=.SQLExpress; Database=NHCookbook; Trusted_Connection=SSPI"/> </connectionStrings> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> <property name="proxyfactory.factory_class"> NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle </property> <property name="dialect"> NHibernate.Dialect.MsSql2008Dialect, NHibernate </property> <property name="connection.connection_string_name"> db </property> <property name="adonet.batch_size"> 100 </property> </session-factory> </hibernate-configuration> </configuration>
Program.cs
, add the following using
statements:using Eg.ConfORMMapping.Mappings; using NHibernate.Cfg;
Main
method, add the following code:var mappingFactory = new MappingFactory(); var mapping = mappingFactory.CreateMapping(); var nhConfig = new Configuration().Configure(); nhConfig.AddDeserializedMapping(mapping, null); var sessionFactory = nhConfig.BuildSessionFactory(); Console.WriteLine("NHibernate configured!"); Console.ReadKey();
In this recipe, our App.config
is nearly identical to the App.config
from our first configuration recipe. We've simply removed the <mapping>
element that tells NHibernate to load mappings embedded in an assembly. Instead, we use ConfORM to build an HbmMapping
object containing mappings for our entire model. We new up our MappingFactory
and call CreateMapping
.
Next, we build our NHibernate Configuration
object and load the configuration from App.config
.
The real trick of this recipe comes when we call AddDeserializedMapping
. We pass in our HbmMapping
object. As the method name suggests, it really is a deserialized XML mapping, except that we built it with code, not XML. In fact, we could serialize the HbmMapping
object with the .NET XmlSerializer
, and we would get an actual human-readable XML mapping for our model.
Because we build our mapping with code, we get a nice speed boost during configuration compared with normal embedded resource XML mappings and even Fluent NHibernate, which serializes its mappings down to XML, then lets NHibernate deserialize them.