본문 바로가기

IT/C#, NHibernate

FluentNHibernate configure 설정

반응형
먼저 패키지 추가를 한다


참조를 추가를 한다

" 솔루션 탐색기-> 프로젝트의 참조 우클릭 - > 참조 추가 -> 찾아보기  ->
      Iesi.Collections.dll, NHibernate.dll "  추가



Configure 하는 클래스를 작성한다


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;

namespace hibernateTest1
{
    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.MsSql2012.ConnectionString(
                                  @"Server=localhost;initial catalog=DB명;user=sa;password=********;" )
                              .ShowSql()
                )
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf< Program>())
                .ExposeConfiguration(cfg => new SchemaExport (cfg).Create(true, true))
                .BuildSessionFactory();
        }

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


DB 데이터 추가하는 기능을 작성한다

  class Program
    {
       
        static void Main(string[] args)
        {
              using (var session = NHibernateHelper.OpenSession())
              {
                  using(var transaction = session.BeginTransaction())
                  {
                      var d = new Data { Value = 1.1f, Name= "ss", datetime="22:22" };
                      session.Save(d);
                      transaction.Commit();

                  }
              }
        }
      
    }



출처  : codeproject