Click here to Skip to main content
13,589,969 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


38 bookmarked
Posted 25 Dec 2011
Licenced CPOL

Start Fluent NHibernate

, 25 Dec 2011
Rate this:
Please Sign up or sign in to vote.
Start your project from Visual Studio and say GoodBye to SQL Server and Tables


Start your project from Visual Studio and say GoodBye to SQL Server and Tables.

What is NHibernate? Why do we use this technology? How to start using NHibernate?

NHibernate is an ORM (Object Relational Mapping) that maps relational data and objects. When you use NHibernate, you don't have to start from creating tables but all you have is to write your entities classes according to your business and NHibernate will create the tables for you.

We (applications developers) use NHibernate to avoid the stress of using, analyzing and changing the database. Using NHibernate will avoid the need from even entering your DBMS, When you have to change anything in some table, all you have is just modify your entity rather than enter the DB and change columns and relations... etc.

This article will give all what you need to get the confidence and continue with NHibernate.

Step 1: Create Your Business Entities

The first step is creating your entities in your project:

public class Employee
        public virtual int Id {get; set;}
        public virtual string FirstName {get; set;}
        public virtual string Position {get; set;}
        public virtual Department EmployeeDepartment  
		{get; set;} // Represent the relation between Employee and Department
public class Department
        public virtual int Id {get; set;}
        public virtual string Name {get; set;}
        public virtual string PhoneNumber {get; set;}

Remember to add virtual keyword to your property, that is used by NHibernate that will create proxy at runtime to allow lazy load (you can skip it for now, I will discuss in depth in my next article.)

Step 2: Create the Map Entities

Now you have to create a map entity for every entity created before that represents the heart of NHibernate. Any future change that happened on the entity should change the map here too:

class EmployeeMap : ClassMap<employee /><Employee>
        public EmployeeMap()
            Id(x => x.Id);

            Map(x => x.FirstName);

            Map(x => x.Position);

            References(x => x.EmployeeDepartment).Column("DepartmentId");

class DepartmentMap : ClassMap<department /><Department>
        public DepartmentMap()
            Id(x => x.Id);

            Map(x => x.Name);

            Map(x => x.PhoneNumber);


Remember to add virtual keyword to your property, that is used by NHibernate that will create proxy at runtime to allow lazy load (in my articles, I focus on how we use this technology more than why we use it and what are the issues that need a lot of discussion, if you need more).

NHibernate methods (keywords):

  • Map: Used to create column for the selected property
  • References: Used to create many-to-one relation, applied in the many side
  • Table: Determine the name of the table (optional)

Step 3: Create the Configuration

Now you have to write the configuration lines that will be written just one time, every execution for your program will execute these lines that will modify the database according to your update:

public class NHibernateHelper
        private static ISessionFactory _sessionFactory;

        private static ISessionFactory SessionFactory
                if (_sessionFactory == null)

                return _sessionFactory;

        private static void InitializeSessionFactory()
            _sessionFactory = Fluently.Configure()
                  @"Server=(local);initial catalog=xxxxx;
		user=xxxxx;password=xxxxx;") // Modify your ConnectionString
                .Mappings(m =>
                .ExposeConfiguration(cfg => new SchemaExport(cfg)
                                                .Create(true, true))

        public static ISession OpenSession()
            return SessionFactory.OpenSession();

Now all you have is just run your application and go to the SQL Server to see your tables.

Note: Don't forget to modify the ConnectionString.

Step 4: Insert your Data to Test the Project

Now you have to save some rows into your database by writing these lines in the MAIN:

static void Main(string[] args)
            using (var session = NHibernateHelper.OpenSession())
                 using (var transaction = session.BeginTransaction())
                     var DepartmentObject = new Department 
			{Name = "IT", PhoneNumber = "962788700227" };
                     Console.WriteLine("Department Created: " + DepartmentObject.Name);

Hope this article will give you the fundamentals of Fluent NHibernate.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Omar Alatare
Software Developer
Jordan Jordan
I am Software Developer start programming from vb6(Classic ASP) to VB.Net 2010, I am working with the most popular technologies like Silverlight 4, WCF Services, WPF, WF4 , ASP.Net, ADO.Net, JQuiry, Ajax, Web Services and more.

You may also be interested in...


Comments and Discussions

Questionmapping Pin
pedrorene27-Jan-16 11:07
memberpedrorene27-Jan-16 11:07 
Questionmissing components Pin
Lester Espiritu27-Dec-15 19:32
memberLester Espiritu27-Dec-15 19:32 
Question原谅我不会说英文 >_< 关于Fluent NHibernate 数据库连接的问题, Pin
Member 1216564224-Nov-15 22:45
memberMember 1216564224-Nov-15 22:45 
GeneralThank you! Pin
Tasos Panagis11-Sep-14 22:33
memberTasos Panagis11-Sep-14 22:33 
QuestionClassMap vs ClassMapping Pin
Wouter Vos20-Jan-14 4:24
memberWouter Vos20-Jan-14 4:24 
GeneralResolve my Problem Pin
Member 1037169830-Nov-13 1:36
memberMember 1037169830-Nov-13 1:36 
QuestionError Pin
akosidab6-Nov-13 1:54
memberakosidab6-Nov-13 1:54 
AnswerRe: Error Pin
SilvioDelgado5-Mar-14 12:18
memberSilvioDelgado5-Mar-14 12:18 
Questionadding one to many object to db Pin
Member 100042699-Aug-13 18:04
memberMember 100042699-Aug-13 18:04 
AnswerRe: adding one to many object to db Pin
Sebek Kaa5-Jan-15 3:20
memberSebek Kaa5-Jan-15 3:20 
GeneralMy vote of 5 Pin
Md. Rashidul Hasan Masum24-Jul-13 13:34
memberMd. Rashidul Hasan Masum24-Jul-13 13:34 
QuestionIssue with running application Pin
Vishal_00716-Jan-13 2:06
memberVishal_00716-Jan-13 2:06 
AnswerRe: Issue with running application Pin
Zouzou_J4-Feb-13 3:56
memberZouzou_J4-Feb-13 3:56 
GeneralRe: Issue with running application Pin
slaphead9910-Feb-14 1:42
memberslaphead9910-Feb-14 1:42 
Generalnice Pin
Lokesh_19374448-Sep-12 17:36
memberLokesh_19374448-Sep-12 17:36 
QuestionGreat article Pin
Browski19-Jun-12 7:35
memberBrowski19-Jun-12 7:35 
GeneralNice! Pin
akpsi16-May-12 0:57
memberakpsi16-May-12 0:57 
GeneralMy vote of 5 Pin
BartekSurowiec26-Dec-11 14:14
memberBartekSurowiec26-Dec-11 14:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04 | 2.8.180618.1 | Last Updated 25 Dec 2011
Article Copyright 2011 by Omar Alatare
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid