使用NHibernate3.0来构建自己的ORM框架(一)

时间:2022-11-06 03:08:43

1. Library文件

  需要的dll文件如下:

  FluentNHibernate.dll (*)

  NHibernate.ByteCode.Castle.dll (*)

  NHibernate.dll (*)

  Remotion.Data.Linq.dll

  Antlr3.Runtime.dll

  Castle.Core.dll

  Iesi.Collections.dll

 

2. 创建Hibernate访问通用类

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

namespace CsharpTrainer.NHibernate3
{
     public  class NHibernateDb<TMap> : IDisposable
    {
         private  string connString;
         private ISessionFactory sessFactory;
         private ISession session;

         public ISessionFactory SessionFactory
        {
             get {  return sessFactory; }
             set { sessFactory = value; }
        }

         public ISession Session
        {
             get {  return session; }
             set { session = value; }
        }

         public  void Dispose()
        {
            session.Dispose();
        }

         public NHibernateDb( string pStr)
        {
            connString = pStr;
            sessFactory = CreateSessionFactory();
            session = sessFactory.OpenSession();
        }

        ~NHibernateDb()
        {
             try
            {
                Dispose();
            }
             catch 
            {
                Console.WriteLine( " Exception: session dispose failed! ");
            }
        }

         private ISessionFactory CreateSessionFactory()
        {
             return Fluently.Configure()
                .Database(MsSqlConfiguration
                              .MsSql2008
                              .ConnectionString(connString))
                .Mappings(m => m.FluentMappings
                                   .AddFromAssemblyOf<TMap>())
                .BuildSessionFactory();
        }
        
         private  void CreateSchema(Configuration cfg)
        {
             var schemaExport =  new SchemaExport(cfg);
            schemaExport.Drop( falsetrue);
            schemaExport.Create( falsetrue);
        }

         public  void CreateDatabase()
        {
            Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(connString))
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<TMap>())
                .ExposeConfiguration(CreateSchema)
                .BuildConfiguration();
        }
    }
}

 

3. 创建表格对应的实体类

  我们以Northwind数据库的Employees表格为例

using System;

namespace CsharpTrainer.NHibernate3.Entities
{
     public  class Employees
    {
         public  virtual  int EmployeeID {  getset; }
         public  virtual  string LastName {  getset; }
         public  virtual  string FirstName {  getset; }
         public  virtual  string Title {  getset; }
         public  virtual DateTime BirthDate {  getset; }
         public  virtual  string Address {  getset; }
         public  virtual  string City {  getset; }
         public  virtual  string Region {  getset; }
         public  virtual  string Country {  getset; }
         public  virtual  string Notes {  getset; }

         public  override  string ToString()
        {
             string format =  " Employee ID: {0}\nLast Name: {1}\n "
                          +  " First Name: {2}\nTitle: {3}\nBirth Date: {4}\n "
                          +  " Address: {5}\nCity: {6}\nRegion: {7}\nCountry: {8}\n "
                          +  " Notes: {9}\n ";

             return  string.Format(format, EmployeeID, LastName, FirstName,
                                    Title, BirthDate, Address, City, Region, Country, Notes);
        }
    }
}

 

4. 建立映射关系(映射类)

  EmployeeMap Class:

using FluentNHibernate.Mapping;
using CsharpTrainer.NHibernate3.Entities;

namespace CsharpTrainer.NHibernate3.Mapping
{
     public  class EmployeeMap : ClassMap<Employees>
    {
         public EmployeeMap()
        {
            Id(x => x.EmployeeID,  " EmployeeID ");
            Map(x => x.LastName)
                .Length( 20)
                .Not.Nullable();
            Map(x => x.FirstName)
                .Length( 10)
                .Not.Nullable();
            Map(x => x.Title)
                .Length( 30);
            Map(x => x.BirthDate);
            Map(x => x.Address)
                .Length( 60);
            Map(x => x.City)
                .Length( 15);
            Map(x => x.Region)
                .Length( 15);
            Map(x => x.Country)
                .Length( 15);
            Map(x => x.Notes);
        }
    }
}

 

5. 客户端查询代码

  查询所有的员工,按照LastName排序

 

public  void Run()
        {
             string connStr = ConfigurationManager.ConnectionStrings[ " NorthwindConnStr "].ConnectionString;

             try
            {
                NHibernateDb<EmployeeMap> db =  new NHibernateDb<EmployeeMap>(connStr);

                ISessionFactory factory = db.SessionFactory;
                 using ( var session = factory.OpenSession())
                {
                     var employees = session.QueryOver<Employees>()
                                    .OrderBy(a => a.LastName).Asc
                                    .List();
                    Console.WriteLine( " All Employees Below: ");
                     foreach ( var employee  in employees)
                    {
                        Console.WriteLine(employee);
                    }
                }
                
            }
             catch (Exception ex)
            {
                Console.WriteLine( " Exception:  " + ex.ToString());
            }
        }