NHibernate 3.2 使用 Conformist 进行 CodeFirst 开发

NHibernate 3.2 GA 正式版于 2011-07-30 发布,这一版本对 CodeFirst 的支持性更好了,因为它提供了 Conformist 取代之前第三方的 ConfOrm。

 

NHibernate 3.2 下载地址:http://sourceforge.net/projects/nhibernate/files/NHibernate/

 

下面将讲一下如何使用这一新成员进行数据库的基本操作。我使用的开发环境是:VS2010 + NHibernate 3.2 + MVC 3,下面是项目目录图:

 

 

 

项目只要引用 “Iesi.Collections.dll” 和 “NHibernate.dll” 两个类库文件即可。 

 

 NHibernateCfg 代码:

注意,“MsSql2005Dialect” 表示使用SQL 2005数据库,数据库名为“DiPiPiDB”。

 Code Snippet

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5.  
  6. using NHibernate.Cfg;
  7. using NHibernate.Dialect;
  8. using NHibernate.Driver;
  9. using NHibernate.Mapping.ByCode;
  10.  
  11. namespace DiPiPi.Mvc3.Orm
  12. {
  13.     public static class NHibernateCfg
  14.     {
  15.         private const string _ConnectionString =
  16.         @"Data Source=localhost;Initial Catalog=DiPiPiDB;Integrated Security=True;Pooling=False";
  17.  
  18.         public static Configuration GetConfiguration()
  19.         {
  20.  
  21.             var configure = new Configuration();
  22.  
  23.             configure.SessionFactoryName("DiPiPiDB");
  24.             
  25.            
  26.             configure.DataBaseIntegration(db =>
  27.             {
  28.                 db.Dialect<MsSql2005Dialect>();
  29.                 db.Driver<SqlClientDriver>();
  30.                 db.ConnectionString = _ConnectionString;
  31.             });
  32.  
  33.             

 

 

 ISessionManager 代码:

 

 Code Snippet

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. using NHibernate;
  7.  
  8. namespace DiPiPi.Mvc3.Orm
  9. {
  10.     public interface ISessionManager
  11.     {
  12.         ISessionFactory GetSession();
  13.  
  14.         void CreateDataTable();
  15.  
  16.         void DropDataTable();
  17.     }

 

SessionManager 代码:

 Code Snippet

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5.  
  6. using NHibernate;
  7. using NHibernate.Cfg;
  8. using NHibernate.Cfg.MappingSchema;
  9. using NHibernate.Tool.hbm2ddl;
  10. using NHibernate.Mapping.ByCode;
  11.  
  12. namespace DiPiPi.Mvc3.Orm
  13. {
  14.     /// <summary>
  15.     /// 使用 NHibernate 操作数据库的Session
  16.     /// </summary>
  17.     public class SessionManager : ISessionManager
  18.     {
  19.         private Configuration conf = null;
  20.         private ISessionFactory sessionFactory = null;
  21.         private ModelMapper mapper = null;
  22.  
  23.         public SessionManager()
  24.         {
  25.             mapper = new ModelMapper();
  26.             conf = NHibernateCfg.GetConfiguration();
  27.  
  28.             LoadOrmMapping();
  29.  
  30.         }
  31.  
  32.         public Configuration GetConfiguration()
  33.         {
  34.  
  35.             return conf;
  36.  
  37.         }
  38.  
  39.         private void LoadOrmMapping()
  40.         {
  41.  
  42.             //在Configuration中添加HbmMapping
  43.             AddMapping<UserInfoMap>();
  44.  
  45.             var hbmMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
  46.             conf.AddMapping(hbmMapping);
  47.  
  48.             //Console.WriteLine(hbmMapping.AsString());
  49.  
  50.         }
  51.  
  52.  
  53.         private void AddMapping<TModel>() where TModel : IConformistHoldersProvidernew()
  54.         {
  55.  
  56.             mapper.AddMapping<TModel>();
  57.  
  58.         }
  59.  
  60.  
  61.  
  62.         public ISessionFactory GetSession()
  63.         {
  64.  
  65.             //配置数据库
  66.             SchemaMetadataUpdater.QuoteTableAndColumns(conf);
  67.  
  68.             //建立SessionFactory
  69.             sessionFactory = conf.BuildSessionFactory();
  70.  
  71.             return sessionFactory;
  72.         }
  73.  
  74.  
  75.  
  76.         public void CreateDataTable()
  77.         {
  78.  
  79.             //配置数据库
  80.             SchemaMetadataUpdater.QuoteTableAndColumns(conf);
  81.             //创建数据库
  82.             new SchemaExport(conf).Create(falsetrue);
  83.         }
  84.  
  85.         public void DropDataTable()
  86.         {
  87.  
  88.             //配置数据库
  89.             SchemaMetadataUpdater.QuoteTableAndColumns(conf);
  90.             //删除数据库
  91.             new SchemaExport(conf).Drop(falsetrue);
  92.         }
  93.  
  94.         public ISession OpenSession()
  95.         {
  96.             if (sessionFactory != null)
  97.             {
  98.                 return sessionFactory.OpenSession();
  99.             }
  100.             else
  101.             {
  102.                 return null;
  103.             }
  104.         }
  105.  
  106.         public void CloseSession()
  107.         {
  108.             if (sessionFactory != null)
  109.             {
  110.                 sessionFactory.Close();
  111.             }
  112.  
  113.         }
  114.  
  115.  
  116.     }
  117. }

 

 UserInfo 实体类代码:

  Code Snippet

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5.  
  6. namespace DiPiPi.Mvc3.Orm
  7. {
  8.     public class UserInfo
  9.     {
  10.         public virtual int UserId { getset; }
  11.  
  12.         public virtual string UserName { getset; }
  13.  
  14.     }
  15. }

 

 UserInfoMap 实体映射类代码:

 注意,这里开始使用 Conformist 了,“Generators.Identity”表示主键为整型自增,如果是“Generators.Guid” 表示采用Guid方式,还有其他方式,大家可以去研究。

  Code Snippet

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5.  
  6. using NHibernate.Mapping.ByCode;
  7. using NHibernate.Mapping.ByCode.Conformist;
  8.  
  9. namespace DiPiPi.Mvc3.Orm
  10. {
  11.     /// <summary>
  12.     /// http://taven.cnblogs.com
  13.     /// 
    李锡远的博客
  14.     /// 
    实体映射类
  15.     /// </summary>
  16.     public class UserInfoMap : ClassMapping<UserInfo>
  17.     {
  18.         public UserInfoMap()
  19.         {
  20.             Id(entity => entity.UserId, map =>
  21.                 {
  22.                     map.Column("UserInfoID");
  23.                     map.Generator(Generators.Identity);
  24.                 });
  25.  
  26.             Property(entity => entity.UserName, map => map.Length(150));
  27.  

 

 UserInfoRepository 数据库读取的仓储类代码:(这个类包含了数据库的 增、删、改 常用方法)

 Code Snippet

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5.  
  6. using NHibernate.Criterion;
  7.  
  8. namespace DiPiPi.Mvc3.Orm
  9. {
  10.     public class UserInfoRepository
  11.     {
  12.         private ISessionManager sessionManage;
  13.  
  14.         public UserInfoRepository(ISessionManager _sessionManage)
  15.         {
  16.             sessionManage = _sessionManage;
  17.         }
  18.  
  19.         public List<UserInfo> FindAll()
  20.         {
  21.             using (var session = sessionManage.GetSession().OpenSession())
  22.             {
  23.                 var query = session.QueryOver<UserInfo>()
  24.                 .OrderBy(p => p.UserId).Asc
  25.                 .List();
  26.  
  27.                 return query.ToList();
  28.             }
  29.         }
  30.  
  31.         public List<UserInfo> Find(ICriterion condition)
  32.         {
  33.             using (var session = sessionManage.GetSession().OpenSession())
  34.             {
  35.                 var query = session.QueryOver<UserInfo>()
  36.                 .Where(condition)
  37.                 .OrderBy(p => p.UserId).Asc
  38.                 .List();
  39.  
  40.                 return query.ToList();
  41.             }
  42.         }
  43.  
  44.         public List<UserInfo> FindbyExample(UserInfo entity)
  45.         {
  46.             using (var session = sessionManage.GetSession().OpenSession())
  47.             {
  48.                 var query = session.CreateCriteria<UserInfo>().Add(Example.Create(entity)).List<UserInfo>();
  49.  
  50.                 return query.ToList();
  51.             }
  52.         }
  53.  
  54.         public void Save(UserInfo model)
  55.         {
  56.             using (var session = sessionManage.GetSession().OpenSession())
  57.             {
  58.                 using (var trans = session.BeginTransaction())
  59.                 {
  60.                     
  61.                     session.Save(model);
  62.                     trans.Commit();
  63.                 }
  64.             }
  65.         }
  66.  
  67.         public void Modify(UserInfo model)
  68.         {
  69.             using (var session = sessionManage.GetSession().OpenSession())
  70.             {
  71.                 using (var trans = session.BeginTransaction())
  72.                 {
  73.                     session.Update(model);
  74.                     trans.Commit();
  75.                 }
  76.             }
  77.         }
  78.  
  79.         public void Remove(UserInfo entity)
  80.         {
  81.             using (var session = sessionManage.GetSession().OpenSession())
  82.             {
  83.                 using (var trans = session.BeginTransaction())
  84.                 {
  85.                     session.Delete(entity);
  86.  
  87.                     trans.Commit();
  88.                 }
  89.             }
  90.         }
  91.  
  92.         public void RemoveByID(int Id)
  93.         {
  94.             using (var session = sessionManage.GetSession().OpenSession())
  95.             {
  96.                 using (var trans = session.BeginTransaction())
  97.                 {
  98.                     session.CreateQuery("delete UserInfo where UserId = :userId").SetInt32("userId", Id).ExecuteUpdate();
  99.  
  100.                     trans.Commit();
  101.                 }
  102.             }
  103.         }
  104.  
  105.         public void Removes(String userName

 

 

 将实体代码写好后,执行下面代码可直接创建数据库的表:

 Code Snippet

  1. ISessionManager session = new SessionManager();
  2.  
  3. session.CreateDataTable();

 

执行下面代码可插入数据:

 Code Snippet

  1. ISessionManager session = new SessionManager();
  2. UserInfoRepository userinfoR = new UserInfoRepository(session);
  3. for (var i = 0; i < 10; i++)
  4. {
  5.     UserInfo u = new UserInfo();
  6.     u.UserName = "
    远哥"
    +i;
  7.  
  8.     userinfoR.Save(u);
  9. }

 

执行下面代码可读取数据:

Code Snippet
  1. ISessionManager session = new SessionManager();
  2.  
  3. UserInfoRepository userinfoR = new UserInfoRepository(session);
  4. List<UserInfo> list = userinfoR.FindAll();

 

 

项目源码打包下载:http://files.cnblogs.com/taven/DiPiPiDemo.rar

 

 

posted @ 2011-08-18 18:03  远哥  阅读(4771)  评论(12编辑  收藏