NHibernate配置 使用经验

NHibernate 是数据持久化框架

持久化:保存在存储文件中,如Access XML SQLServer 等数据库或文件中

第一步配置:

<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>

在Web.Config 中的 ConfigSections 加入节点

NHibernate.Cfg.ConfigurationSectionHandler 类实现了 System.Configuration.IConfigurationSectionHandler 接口

Create 方法创建了配置对象并由.net 内置配置管理器加入字典集合

最终加入字典对象类型为 NHibernate.Cfg.Configuration

第二步Nhibernate 节点配置

在Web.Config 的根目录下加入刚刚配置的section,节点名称用section 里配置的name属性

<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2"></hibernate-configuration>

注意:xmlns="urn:nhibernate-configuration-2.2"属性很重要.他告诉当前配置信息适用于NHibernate的版本,

主要是 2.2这个版本信息,要跟您使用的NHibernate版本相吻合.

hibernate-configuration的配置内容

<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Server=localhost;initial catalog=database;uid=test;pwd=test;</property>
<property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<mapping assembly="App.Model"/>

connection.driver_class 告诉NHibernate 配置管理器连接数据库所使用的类型,

这里使用了 SqlServer的类型 NHibernate 支持的类型可以使用Reflector工具进行查看,Driver 命名空间下有所有被支持的连接类型

connection.connection_string 告诉NHibernate 配置管理器连接数据库所使用的字符串

dialect  告诉NHibernate 配置管理器当前连接数据库和.Net之前数据类型的映射

proxyfactory.factory_class 这个不清楚具体有什么作用.正在研究中

mapping 节点可以多个,告诉NHibernate 配置管理器要做对象影射的程序集,他会自动到这个程序中查找xml资源文件,并尝试转换成NHibernate中的Mapping

完成以上两步Nhibernate的基本配置已算完成.其中还有一个配置方式是使用独立的配置文件.文件名必须为 hibernate.cfg.xml

第三步应用到NHibernate的配置信息.包括环境配置和对象关系映射配置

激活醑置的方法在应用程序启动时只能运行一次.

所以建议如果是WEB应用,应将激活醑置放在Global 中 Application_Start方法中 然后调用

首先实例化一个Configuration对象

然后调用 Configure() 方法

到些所有配置已全部完成,并载入到内存中,

注意: 要Mapping 的程序集xml配置文件属性要选 "嵌入的资源" xml文件中的类型名称注意大小写区分, 类型一定要加上程序集名称(全名称) 注意强命名的程序集

原文地址:https://www.cnblogs.com/hznet/p/2054154.html