Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Start Fluent NHibernate

4.81/5 (18 votes)
25 Dec 2011CPOL2 min read 109.6K   5.9K  
Start your project from Visual Studio and say GoodBye to SQL Server and Tables

Introduction

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:

C#
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
    }
C#
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:

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

            Map(x => x.FirstName);

            Map(x => x.Position);

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

            Table("Employee");
        }
    }
C#
class DepartmentMap : ClassMap<department /><Department>
    {
        //Constructor
        public DepartmentMap()
        {
            Id(x => x.Id);

            Map(x => x.Name);

            Map(x => x.PhoneNumber);

            Table("Department");
        }
    }

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:

C#
public class NHibernateHelper
    {
        private static ISessionFactory _sessionFactory;

        private static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)

                    InitializeSessionFactory();
                return _sessionFactory;
            }
        }

        private static void InitializeSessionFactory()
        {
            _sessionFactory = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008
                  .ConnectionString(
                  @"Server=(local);initial catalog=xxxxx;
		user=xxxxx;password=xxxxx;") // Modify your ConnectionString
                              .ShowSql()
                )
                .Mappings(m =>
                          m.FluentMappings
                              .AddFromAssemblyOf<Program>())
                .ExposeConfiguration(cfg => new SchemaExport(cfg)
                                                .Create(true, true))
                .BuildSessionFactory();
        }

        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:

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

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

License

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