Click here to Skip to main content
Click here to Skip to main content

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

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:

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>
    {
        //Constructor
        public EmployeeMap()
        {
            Id(x => x.Id);

            Map(x => x.FirstName);

            Map(x => x.Position);

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

            Table("Employee");
        }
    }
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:

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:

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)

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.

Comments and Discussions

 
QuestionGreat article PinmemberBrowski19-Jun-12 7:35 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140718.1 | Last Updated 25 Dec 2011
Article Copyright 2011 by Omar Alatare
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid