使用NHibernate遭遇unknown entity class问题

我是NHibernate初学者,写一个最初级的NHibernate程序操作Postgresql数据库遇到错误,附上源代码请帮忙看看。

 

hibernate.cfg.xml:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="connection.driver_class">NHibernate.Driver.NpgsqlDriver</property>
    <property name="connection.connection_string">Driver={PostgreSQL UNICODE};Server=localhost;Port=5432;Database=test;Uid=postgres;Pwd=pass123;</property>
    <property name="dialect">NHibernate.Dialect.PostgreSQL81Dialect</property>
    <property name="show_sql">true</property>
  </session-factory>
</hibernate-configuration>

mapping文件(player.hbm.xml),已经配置为嵌入资源:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="TestNHibernate" namespace="TestNHibernate">
  <class name="TestNHibernate.Player" table="Player">
    <id name="ID" column="ID">
      <generator class="increment" />
    </id>
    <property name="PlayerName" />
    <property name="Country" />
  </class>
</hibernate-mapping>

实体类:

namespace TestNHibernate
{

  public class Player
    {
        public virtual int ID { get; set; }
        public virtual string PlayerName { get; set; }
        public virtual string Country { get; set; }
    }

}

数据库访问代码:

    Configuration cfg = new Configuration().Configure();

            ISession session = cfg.BuildSessionFactory().OpenSession();

            Player player = new Player();
            player.PlayerName = "Maradona";
            player.Country = "Argentina";

            session.Save(player);

    session.Close();

在session.Save一行出错:unknown entity class: TestNHibernate.Player

 

不知道为什么系统没有找到Player类的映射关系。

  • admin - 1年前

    Configuration cfg = new Configuration().Configure();

    是读取hibernate.cfg.xml里面的设置配置SessionFactory,你在hibernate.cfg.xml没有配置Mapping。

    可以使用下面两种方法:

    1。可以在hibernate.cfg.xml里面加上Mapping配置<mapping assembly="程序集名称"/>

    2。可以用Configuration类的一些AddXXX方法

    例如:让NHibernate自动到程序集加载所有的嵌入式资源xml映射文件,NHibernate会自动到应用程序集里查找所有的以.hbm.xml结尾的资源文件。

    Configuration cfg = new Configuration()
        .AddAssembly( "NHibernate.Auction" );