Fluent NHibernate 提供object To XML的支持,让我们可以直接在代码中编写NHibernate的Cfg配置文件。
配置文件编写过程,总共分为4步:
1, Fluently.Configure() 生成Cfg对象。
2,.DataBase(x=>xxxxx) 生成数据库对象。
3,.Mapping(x=>xxxx) 匹配Hbm描述。
4,.BuildingSessionFactory 创建状态工厂。
我这里对应Mysql配置文件提取出一个通用泛型SessionFactory工厂。
private static object lockobject = new object();
private Dictionary<string,ISessionFactory> m_SessionFactoryDictionary = new Dictionary<string,ISessionFactory>();
public ISessionFactory CreateSessionFactory<T>(string connectStringName)
{
if (!m_SessionFactoryDictionary.ContainsKey(connectStringName))
{
lock (lockobject)
{
if (!m_SessionFactoryDictionary.ContainsKey(connectStringName))
{
m_SessionFactoryDictionary[connectStringName] = Fluently.Configure()
//配置数据库
.Database(
FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard.ConnectionString(
x => x.FromAppSetting(connectStringName)))//connectStringName是AppSetting中的链接字符串
.Mappings(x => x.FluentMappings.AddFromAssemblyOf<T>())
.BuildSessionFactory();
}
}
return m_SessionFactoryDictionary[connectStringName];
}
return m_SessionFactoryDictionary[connectStringName];
}
private Dictionary<string,ISessionFactory> m_SessionFactoryDictionary = new Dictionary<string,ISessionFactory>();
public ISessionFactory CreateSessionFactory<T>(string connectStringName)
{
if (!m_SessionFactoryDictionary.ContainsKey(connectStringName))
{
lock (lockobject)
{
if (!m_SessionFactoryDictionary.ContainsKey(connectStringName))
{
m_SessionFactoryDictionary[connectStringName] = Fluently.Configure()
//配置数据库
.Database(
FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard.ConnectionString(
x => x.FromAppSetting(connectStringName)))//connectStringName是AppSetting中的链接字符串
.Mappings(x => x.FluentMappings.AddFromAssemblyOf<T>())
.BuildSessionFactory();
}
}
return m_SessionFactoryDictionary[connectStringName];
}
return m_SessionFactoryDictionary[connectStringName];
}
类似Oracle,SqlServer也可以这样建立SessionFactory
运行时候Mysql会要求加载对应的NHibernate.MysqlDriver.
1, Mysql支持。
下载Mysql驱动。
http://mysql.spd.co.il/Downloads/Connector-Net/mysql-connector-net-6.2.4.zip
安装后,用VS的Reference引用Mysql.Data.dll并且设置属性为Copy Local:True
支持Windows 64bit。设置工程Platform target:Any CPU (原来是X86)