在ASP.NET項目中使用NHibernate老是會碰到無法載入設定檔的問題,剛才瞎折騰了1小時,才從外國的一篇部落格裡找到瞭解決方案.地址如下:http://derek-says.blogspot.com/2008/02/nhibernate-in-visual-web-developer.html.
現在我來簡單的講解下如何配置.
1.資料庫裡建表,如tb_Department
2.然後編寫對應的類檔案, 如我對應類的全名是:NetFuture.NHibernateClass.NH_tb_Department
3.在WebConfig中加入配置,一下是我的設定檔:
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">
NHibernate.Connection.DriverConnectionProvider
</property>
<property name="dialect">
NHibernate.Dialect.MsSql2000Dialect
</property>
<property name="connection.driver_class">
NHibernate.Driver.SqlClientDriver
</property>
<property name="connection.connection_string">
Data Source=(local);Integrated Security=True; initial catalog=DB_PersonnelManageSystem
</property>
<mapping assembly="App_Code"/>
</session-factory>
</hibernate-configuration>
紅色的那句貌似是關鍵的地方.
4.編寫類對應的對應檔,如:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false">
<class name="NetFuture.NHibernateClass.NH_tb_Department, App_Code" table="tb_Department" >
<id name="DepartmentId" column="DepartmentId" type="Int32" length="4" unsaved-value="0">
<generator class="native" />
</id>
<property name="DepartmentName" column="DepartmentName" type="String" length="16" />
<property name="Description" column="Description" type="String" length="200" />
<property name="ManagerId" column="ManagerId" type="String" length="15" />
</class>
</hibernate-mapping>
紅色的那句也是關鍵的地方.
5.將類與對應檔都放置與App_Code檔案夾下
6.編寫類似下面的NHibernate初始化配置代碼:
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
cfg.AddDirectory(new System.IO.DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath(@"~/App_Code/")));
_factory = cfg.BuildSessionFactory();
這樣就完成了對App_Code檔案夾的映射,NHibernate就會在其中搜尋設定檔了.
第一次寫隨筆,希望能對你有所協助^_^.