Configuration of NHibernate through app.config file

Ahamed Fazil Buhari
 
Senior Developer
September 15, 2017
 
Rate this article
 
Views
4869

Hello everyone, in this article we will see how to use Nhiberate in you C# code. Before going deep into NHibernate I would like to give some basic information about this magical DB connector. NHibernate is an object-relational mapping (ORM) solution for the Microsoft .NET platform. It provides a framework for mapping an object-oriented domain model to a traditional relational database (from Wikipedia).

Before we start, add NHibernate reference to your solution from NuGet Package. Here I’m using the version 4.1.1.4

 

image

 

You can refer the nhibernate config in the app.config file or you can have separate config file. It is good practice to have that in separate config file and refer that file in app.config file.

Also here I have used log4net for logging. And this will be used along with Nhibernate while configuration.

 

image

 <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
   <session-factory>
     <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
     <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
     <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
     <property name="connection.connection_string">Data Source=*****;database=****;Integrated Security=True;</property>
     <property name="show_sql">true</property>
     <property name="adonet.batch_size">100</property>
   </session-factory>
 </hibernate-configuration>
 

In app.config, refer your hibernated configured .config file by using the below tag,

image

 

image

 

 

Use the below code to create Database, here it first checks whether the Database with that name already exists or not, if not exists then it will create new Database.

 using NHibernate;
 using NHibernate.Mapping.ByCode;
 using NHibernate.Mapping.ByCode.Conformist;
 using NHibernate.Tool.hbm2ddl;
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using Ncfg = NHibernate.Cfg;
 namespace MySolution
 {
 public class DataBaseOperations
     {
         private Ncfg.Configuration _configuration;
         private ISessionFactory _sessionFactory;
         private ISession _session;
 
         public DataBaseOperations()
         {
       //Configuration values are taken from .config file
             _configuration = new Ncfg.Configuration();
             _configuration.Configure();
             var mapper = new ModelMapper();
             mapper.AddMapping(typeof(HibDataBaseMapping));
             _configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
         }
 
         public void CreateDatabaseSchema()
         {
             ValidateSchema(_configuration);
         }
         public void ValidateSchema(Ncfg.Configuration config)
         {
             try
             {
                 new SchemaValidator(config).Validate();
             }
             catch
             {
                 new SchemaExport(_configuration).Create(false, true);
             }
         }
 
 	//Mapping using Nhibernate class mapping
 	public class HibDataBaseMapping : ClassMapping<HibDataBase>
     	{
         public HibDataBaseMapping()
         {
     //Each table should have unique ID
             Id<int>(x => x.ID);
             Property<string>(x => x.FirstName);
             Property<string>(x => x.LastName);          
             Property<DateTime?>(x => x.UpdatedOn);          
         }
     	}
 	//This will be the Table name and Properties will become colummns
 public class HibDataBase
     	{        
         public virtual int ID { get; set; }
         public virtual string FirstName { get; set; }
         public virtual string LastName { get; set; }       
         public virtual DateTime? UpdatedOn { get; set; }    
 }
     }
 
     class Program
     {
         static void Main(string[] args)
         {
             //Constructor will be called and all config values are set
             DataBaseOperations dbOperation = new DataBaseOperations();
             //Validate Table and create
             dbOperation.CreateDatabaseSchema();
         }
     }
 }
 

Happy Coding

Ahamed

Category : Nhibernate

Author Info

Ahamed Fazil Buhari
 
Senior Developer
 
Rate this article
 
Ahamed is a Senior Developer and he has very good experience in the field of Microsoft Technologies, especially SharePoint, Azure, M365, SPFx, .NET and client side scripting - JavaScript, TypeScript, ...read more
 

Leave a comment