In addition to fluent mappings and auto-mappings, the Fluent NHibernate project also brings its own code configuration syntax to NHibernate configuration. In this recipe, I'll show you how to configure NHibernate with the Fluent NHibernate syntax.
Eg.FluentMappings
model and mapping from the Creating Mappings Fluently recipe in Chapter 1.ConfigByFNH
.ConfigByFNH
project, add references to NHibernate.dll
, NHibernate.ByteCode.Castle.dll
, and FluentNHibernate.dll
in the Lib
folder.ConfigByFNH
, add a reference to the Eg.FluentMappings
project.App.config
file with this configuration:<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="db" connectionString="Server=.SQLExpress; Database=NHCookbook; Trusted_Connection=SSPI"/> </connectionStrings> </configuration>
Program.cs
, add the following using
statements:using Eg.FluentMappings.Mappings; using FluentNHibernate.Cfg; using FluentNHibernate.Cfg.Db; using NHibernate.ByteCode.Castle;
Main
method, add this code:var nhConfig = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2008 .ConnectionString(connstr => connstr.FromConnectionStringWithKey("db") ) .ProxyFactoryFactory<ProxyFactoryFactory>() .AdoNetBatchSize(100) ) .Mappings(mappings => mappings.FluentMappings .AddFromAssemblyOf<ProductMapping>() ) .BuildConfiguration(); var sessionFactory = nhConfig.BuildSessionFactory(); Console.WriteLine("NHibernate configured fluently!"); Console.ReadKey();
Our fluent configuration can be broken down in to three parts. First, we configure these properties:
dialect
property to MsSql2008Dialect
when we use the MsSql2008
static property of MsSqlConfiguration
.connection.connection_string_name
is set to db
with a call to FromConnectionStringWithKey
.ProxyFactoryFactory
, we set proxyfactory.factory_class
to the Castle DynamicProxy2 proxy factory.adonet.batch_size
to 100 with a call to AdoNetBatchSize
.Next, we load mappings into our configuration. In this recipe, we load our fluent mappings from Chapter 1. Fluent NHibernate scans the entire assembly and loads all the fluent mappings it finds. Fluent NHibernate allows you to add any combination of fluent mappings, auto-mappings, and standard hbm.xml
mappings.
Finally, from the fluent configuration, we build a standard NHibernate configuration.
3.22.61.218