Another common method for configuring NHibernate uses a .NET configuration file. In this recipe, we will show you how to configure NHibernate using App.config
or Web.config
files, to provide an identical configuration to the previous recipe.
ConfigByAppConfig
to your solution.ConfigByAppConfig
project using the NuGet Package Manager Console.ConfigByAppConfig
, add a reference to the Eg.Core
project.App.config
file to your project.App.config
file.<configSections> <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" /> </configSections>
connectionStrings
section with a connection string:<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="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>
App.config
file should look similar to this:<?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="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
and add using NHibernate.Cfg;
to the beginning of the file.Main
method, add the following code to configure NHibernate:var nhConfig = new Configuration().Configure(); var sessionFactory = nhConfig.BuildSessionFactory(); Console.WriteLine("NHibernate Configured!"); Console.ReadKey();
This recipe works in the same way as the previous recipe. However, in this recipe, we have moved the hibernate-configuration
element from the hibernate.cfg.xml
file to App.config
. The connection.connection_string_name
property references our connection string named db
. We can name the connection string anything we like, as long as this property matches the connection string's name.
18.226.96.155