在ASP.NET配置NHibernate
BabyMaker项目中几个Model之间的关系有一对多,多对多,如果用ORM可以直接对对象进行操作及读取存储List,可以简单很多,还有个就是可以自动建表,我最喜欢的地方。。。.Net下的ORM框架有很多,这里记录下在ASP.NET中配置NHibernate的一些步骤。
首先需要引入Required_Bins和Required_For_LazyLoading\Castle下的所有文件。
然后就可以去配置Web.config了
在configuration下增加一个configSections:
<configSections>
<section name="hibernate-configuration"
type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
</configSections>
这一步是告诉ASP.NET你要配置NHibernate,这个节点必要要放在最前面。
在connectionStrings里增加一个数据库连接字符串
<connectionStrings>
<add name="db" connectionString="Server=.; Database=makebaby; Trusted_Connection=SSPI"/>
</connectionStrings>
接下来增加NHibernate配置信息
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="proxyfactory.factory_class">
NHibernate.ByteCode.Castle.ProxyFactoryFactory,
NHibernate.ByteCode.Castle
</property>
<!-- 2008配置-->
<property name="dialect">
NHibernate.Dialect.MsSql2008Dialect,
NHibernate
</property>
<property name="connection.connection_string_name">
db
</property>
<property name="current_session_context_class">
web
</property>
<property name="adonet.batch_size">
100
</property>
<property name="show_sql">
true
</property>
<property name="hbm2ddl.auto" >
update
</property>
<mapping assembly="Model"/>
</session-factory>
</hibernate-configuration>
session-factory元素里可以配置很多信息,比如数据库连接,是否显示SQL,最大连接数等等。
其中“Model”是我们的包含项目Model的项目,里面有model类和对应的hbm.xml文件;“current_session_context_class”是为了在ASP.NET实现session管理,”web”是让NHibernate在HttpContext.Items这个集合中保存ISession;其他配置和Hibernate基本上一样。
最后我们可以在web程序中的Global的Application_Start方法中实例化我们session工厂了(当然也可以在其他任何地方)
protected void Application_Start(object sender, EventArgs e)
{
new Configuration().Configure().BuildSessionFactory();
}
因为配置了hbm2ddl.auto的value为update,所以是会自动建立或更新数据库表的。
配置搞定,使用的话和Hibernate基本上一样。