概述:
當運行 session.Save(tnp);時,出現這個"Unknown entity class: TestCleanSnow.TestNhibernatePerson"這個異常.
映射文件 TestNhibernatePerson.hbm.xml如下:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="TestCleanSnow" namespace="TestCleanSnow">
<class name="TestCleanSnow.TestNhibernatePerson,TestCleanSnow" table="TEST_NHIBERNATE_PERSON" lazy="false">
<id name="Usertestid" column="USERTESTID" type="Decimal">
<generator class="sequence">
<param name="sequence">emp_sequence</param>
</generator>
</id>
<property type="string" not-null="true" length="6" name="Usertestname" column="USERTESTNAME" />
</class>
</hibernate-mapping>
操作代碼如下:
ISessionFactory factory = config.BuildSessionFactory();
ISession session = factory.OpenSession();
TestNhibernatePerson tnp = new TestNhibernatePerson();
tnp.Usertestname = "test4";
ITransaction trans = session.BeginTransaction();
try
{
// 保存記錄
session.Save(tnp);
trans.Commit();
Console.WriteLine("Insert Success!");
}
catch (Exception ex)
{
trans.Rollback();
Console.WriteLine(ex.Message);
}
finally
{
session.Close();
}
配置代碼app.config如下:
<!-- Add this element -->
<configSections>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
<!--<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />-->
</configSections>
<!-- Add this element -->
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory>
<property name="dialect">NHibernate.Dialect.OracleDialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.connection_string">user id=jkpt;data source=jkorasvr;password=designer;</property>
<property name="connection.isolation" >ReadCommitted</property>
<property name="show_sql">true</property>
<!-- mapping files -->
<mapping assembly="TestCleanSnow" />
</session-factory>
</hibernate-configuration>
說明:在操作代碼中加載相應引用後 config.AddAssembly("TestCleanSnow");,就不出現錯誤.
如果以配置文件的形式加載引用卻出現如題的錯誤.
原因分析:
解決1:
可能是相應的映射文件沒有設置成"嵌入式資源".我這裏相應的映射文件爲 TestNhibernatePerson.hbm.xml.
在解決方案資源管理器中找到TestNhibernatePerson.hbm.xml該映射文件
右擊---屬性----在將“生成操作”設置成“嵌入的資源”.
解決2:
我把 Configuration config = new Configuration();改成 Configuration config = new Configuration().Configure();
讓程序去找hibernate.cfg.xml,這個配置文件的配置跟app.config中的一樣。
解決3:
檢查映射文件映射文件 TestNhibernatePerson.hbm.xml的配置是否正確,其中
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="模塊名稱" namespace="命名空間">
<class name="類名" table="數據庫表名" lazy="false">
<id name="Usertestid" column="USERTESTID" type="Decimal">
//主鍵
<generator class="sequence"> //主鍵生成方式