FluentNHibernate初探[2]

一.写在前面

上一节已经将如何把FluentNHibernate引入到工程中讲过了,这一节我们来看一看如何通过FluentNHibernate来连接到数据库.

 

二.创建NHibernateHelper类

需要连接到数据库的配置将会被封装在这个类中.在配置过程中将会应用到lambda表达式.

本篇将根据Fluent-nhibernate的官方文档,对连接到数据库的配置进行讲解.文档地址:https://github.com/jagregory/fluent-nhibernate/wiki/Fluent-configuration

 

可以通过Fluent NHibernate提供的API在程序中全部使用代码,来完成所有的Hibernate配置.这个API被分成了五个主要的方法,其中三个方法是一定要使用的.

Fluently.Configure()
  .Database(/* your database settings */)
  .Mappings(/* your mappings */)
  .ExposeConfiguration(/* alter Configuration */) // optional
  .BuildSessionFactory();

我们可以通过多种方式混合使用这些方法来创建应用

    • Fluently.Configure 开始配置进程,
    • DataBase是我们确认数据库配置的地方,使用的是database configuration api.
    • Mappings是我们提供我们正在使用的映射.
    • ExposeCOnfigration是可选择的,但它可以更改行Configuration对象.
    • BuildSessionFactory是最后一个被调用的,它会根据我们的配置创建NHibernate SessionFactory的实例.

下面是自己用到的NHibernateHelper的脚本:

 1 using FluentNHibernate.Cfg;
 2 using FluentNHibernate.Cfg.Db;
 3 using NHibernate;
 4 
 5 namespace ARPGPhotonServer.DB
 6 {
 7     internal class NHibernateHelper
 8     {
 9         public static readonly NHibernateHelper Instance = new NHibernateHelper();
10         private ISessionFactory _sessionFactory;
11 
12         private NHibernateHelper()
13         {
14             InitSessionFactory();
15         }
16 
17         public ISession OpenSession()
18         {
19             return _sessionFactory.OpenSession();
20         }
21 
22         private void InitSessionFactory()
23         {
24             _sessionFactory =
25                 Fluently.Configure()
26                     .Database(
27                         MySQLConfiguration.Standard.ConnectionString(
28                             c => c.Server("localhost").Database("arpgserver").Username("root").Password("1234")))
29                     .Mappings(m => m.FluentMappings.AddFromAssemblyOf<ArpgApplication>())
30                     .BuildSessionFactory();
31         }
32     }
33 }

 

posted @ 2015-11-12 14:35  WongSiuming  阅读(543)  评论(0编辑  收藏  举报