Wednesday, January 13, 2010

NHibernate – Configuration (Part 5)


Once we have the domain entities and mapping files ready, we need to tell NHibernate about the database server and how to access it. For this we use a file named NHibernate.cfg.xml to configure NHibernate to access a Microsoft SQL Server 2005 express database.
xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriverproperty>
    <property name="connection.connection_string">Server=(local);Initial Catalog=NHibernateSampleDB;User Id=;Password=property>
    <property name="adonet.batch_size">10property>
    <property name="show_sql">falseproperty>
    <property name="dialect">NHibernate.Dialect.MsSql2005Dialectproperty>
    <property name="use_outer_join">trueproperty>
    <property name="command_timeout">60property>
    <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'property>
    <property name="proxyfactory.factory_class"> NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu property>      
  session-factory>
hibernate-configuration>
This code’s lines specify the following information:
1.       The name of the .NET class implementing the Dialect which enables certain platform dependent features. Despite the ANSI standardization effort, SQL is implemented differently by various databases vendors. So, you must specify a Dialect. NHibernate includes built-in support for most popular SQL databases, and new dialects may be defined easily.
2.       The name of the .NET class implementing the ADO.NET Driver. Note that, since NHibernate 1.2, when using the partial name of a driver which is in the global assembly cache (GAC), you have to add a element in the application configuration file to specify it’s fully qualified name so that NHibernate can successfully load it.
3.       The ConnectionString: the string used to create a database connection as defined by ADO.NET.
NHibenrate allows you to specify the configuration entries in an App.Config/ Web.Config file also. However you may be required to specify the configuration entries under the nhibernate section. I have included the configuration file in a separate project other than the one which has the domain classes. We’ll be using this project for adding our repository classes as well. Another important thing I have done is to mention the output path of all these projects to a common folder.


Next we’ll see how to access this configuration information and create a ISessionFactory instance from the information.

No comments: