본문 바로가기
프로그래밍/DB & Redis

NHibernate

by 뽀도 2015. 8. 4.

 

lazyload : 화면에 보이는 영역에서만 로딩을 하는 기법, 실제 사용자가 보고있는 가시영역만 로딩하는것

 

 

Start Fluent NHibernate

 

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.

반응형

'프로그래밍 > DB & Redis' 카테고리의 다른 글

[mssql] uniquekey 설정, 해제  (0) 2015.08.13
[MSSQL] Union  (0) 2015.08.12
EXISTS로 시작하는 하위 쿼리  (0) 2015.07.29
MS-SQL 다중 업데이트  (0) 2015.07.15
MS_SQL 반복문  (0) 2015.07.14

댓글