-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating
NHibernate 4.x Cookbook - Second Edition
By :
You can also configure NHibernate entirely in code. In this recipe, we'll show you how to do just that.
ConfigByCode.ConfigByCode project using NuGet Package Manager Console.ConfigByCode, add a reference to the Eg.Core 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 NHibernate.Cfg; using NHibernate.Dialect;
Main function, add the following code to configure NHibernate:var nhConfig = new Configuration().DataBaseIntegration(db =>
{
db.Dialect<MsSql2012Dialect>();
db.ConnectionStringName = "db";
db.BatchSize = 100;
});
var sessionFactory = nhConfig.BuildSessionFactory();
Console.WriteLine("NHibernate Configured!");
Console.ReadKey();In this recipe, we create an NHibernate configuration using methods in the NHibernate.Cfg namespace. These methods offer full type safety and improved discoverability over code configurations in the previous version of NHibernate.
We specify dialect, connection.connection_string_name, and adonet.batch_size with the DatabaseIntegration method. Finally, we build a session factory using the BuildSessionFactory method.
Notice that we are still referencing the db connection string defined in our App.config file. If we wanted to eliminate the App.config file entirely, we could hardcode the connection string with this code:
db.ConnectionString = @"Connection string here...";
This, however, is completely inflexible, and will require a full recompile and redeployment for even a minor configuration change.