NHibernate.MappingException:没有持久性:NHibernateExperiment.Player - 我找不到解决方案

时间:2012-06-27 13:33:58

标签: c# .net nhibernate

我尝试使用NHibernate ORM创建一个项目,当我想到我完成的所有内容时,它给了我一个 NHibernate.MappingException:没有持久性异常 我读到问题可能是我没有在配置文件中添加程序集,但是我做了这个,而且它没有修复...

如果有人有痘痘时间,请帮我解决问题。

这里是我调用的代码以添加新的Player对象

private void btnInsert_Click(object sender, EventArgs e)
        {
            Player playerData = new Player();
            SetPlayerInfo(playerData);

            using (ISession session = SessionFactory.OpenSession)
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    try
                    {
                        session.Save(playerData); // here it spits
                        transaction.Commit();
                        GetPlayerInfo();
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        throw ex;
                    }
                }
            }

        }

private void GetPlayerInfo()
        {
            using (ISession session = SessionFactory.OpenSession)
            {
                IQuery query = session.CreateQuery("FROM Player");
                IList<Player> pInfos = query.List<Player>();
                dgvDisplay.DataSource = pInfos;
            }
        }

private void SetPlayerInfo(Player playerData)
        {
            playerData.PlayerName = tbxName.Text;
            playerData.PlayerAge = Convert.ToInt32(tbxAge.Text);
            playerData.DOJ = Convert.ToDateTime(dtpDOJ.Text);
            playerData.BelongsTo = cmbBelongsTo.SelectedItem.ToString();
        }

这里是映射 Player.hbm.xml 代码

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true">
  <class name="NHibernateExperiment.Player, NHibernateExperiment" lazy="true">
    <id name="PlayerId">
      <generator class="native"/>
    </id>
    <property name="PlayerName" column ="PlayerName"/>
    <property name="PlayerAge" column ="PlayerAge"/>
    <property name="DOJ" column="DOJ"/>
    <property name="BelongsTo" column="BelongsTo"/>
  </class>

</hibernate-mapping>

这是 App.config 代码

    <configuration>
  <configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
  </configSections>
  <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.SqlClientDriver</property>
      <property name="connection.connection_string">Server=GRITCAN;database=testDB;Integrated Security=SSPI;</property>
      <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
      <property name="show_sql">true</property>          
      <property name='proxyfactory.factory_class'>NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>          
    </session-factory>
  </hibernate-configuration>
</configuration>

这里是 StackTrace

at NHibernateExperiment.Form1.btnInsert_Click(Object sender,EventArgs e)在E:\ projects \ tests \ NHibernate \ NHibernateExperiment \ NHibernateExperiment \ Form1.cs:第72行 在System.Windows.Forms.Control.OnClick(EventArgs e) 在System.Windows.Forms.Button.OnClick(EventArgs e) 在System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) 在System.Windows.Forms.Control.WmMouseUp(消息&amp; m,MouseButtons按钮,Int32点击) 在System.Windows.Forms.Control.WndProc(消息&amp; m) 在System.Windows.Forms.ButtonBase.WndProc(消息&amp; m) 在System.Windows.Forms.Button.WndProc(消息&amp; m) 在System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m) 在System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp; m) 在System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,Int32 msg,IntPtr wparam,IntPtr lparam) 在System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&amp; msg) 在System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason,ApplicationContext context)中的System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID,Int32 reason,Int32 pvLoopData) ) 在System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason,ApplicationContext context) 在System.Windows.Forms.Application.Run(Form mainForm) at NHibernateExperiment.Program.Main()在E:\ projects \ tests \ NHibernate \ NHibernateExperiment \ NHibernateExperiment \ Program.cs:第16行在System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly,String [] args) at System.AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args)at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 在System.Threading.ThreadHelper.ThreadStart_Context(对象状态) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean ignoreSyncCtx) 在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态) 在System.Threading.ThreadHelper.ThreadStart()

我添加了以下2个对项目的引用 NHibernate.dll NHibernate.ByteCode.LinFu.dll

非常感谢您的帮助!


谢谢BOYS。 .hbm.xml 文件的构建操作内容。 正如你建议我把它改成嵌入式资源,一切正常:)

3 个答案:

答案 0 :(得分:3)

您是否将映射文件设为嵌入式资源?

答案 1 :(得分:2)

检查xml映射是否标记为嵌入资源。另外我建议你使用Fluent nHibernate库 - 这样就可以自由编写大量的xml映射,只有.net类

答案 2 :(得分:0)

工作解决方案:

<强> Form1.cs的     使用NHibernate;     使用NHibernate.Cfg;     使用系统;     使用System.Collections.Generic;     使用System.ComponentModel;     使用System.Data;     使用System.Drawing;     使用System.Linq;     使用System.Text;     使用System.Threading.Tasks;     使用System.Windows.Forms;

namespace NHibernateTutorialPart1
{
    public partial class Form1 : Form
    {

        private Configuration myConfiguration;
        private ISessionFactory mySessionFactory;
        private ISession mySession;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            myConfiguration = new Configuration();
            myConfiguration.Configure("hibernate_mysql.cfg.xml");
            mySessionFactory = myConfiguration.BuildSessionFactory();
            mySession = mySessionFactory.OpenSession();

            using (mySession.BeginTransaction())
            {
                Contact lbContact=new Contact{FirstName="Nisha", LastName="Shrestha",ID=0};
                mySession.Save(lbContact);
                mySession.Transaction.Commit();
            }
        }
    }
}

**hibernate_mysql.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="dialect">NHibernate.Dialect.MySQLDialect</property>
    <property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property>
    <property name="connection.connection_string">
      User Id=root;
      Server=localhost;
      Password=Password1;
      Database=nhibernatecontacts;
    </property>

    <!--This is good for Debugging but not otherwise-->
    <property name="show_sql">true</property>

    <!--<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>-->
    <mapping assembly="NHibernateTutorialPart1"/>
  </session-factory>
</hibernate-configuration>


**contact.hbm.xml**

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="NHibernateTutorialPart1"
                   namespace="NHibernateTutorialPart1">
  <class name="Contact" table="contact">
    <id name="ID" column="ID">
      <generator class="identity" />
    </id>
    <property name="FirstName" />
    <property name="LastName" />
  </class>
</hibernate-mapping>

**Contact class**


namespace NHibernateTutorialPart1
{
    public class Contact
    {

        public virtual int ID { get; set; }
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }

    }
}


**App.config**

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler,NHibernate"/>
  </configSections>
</configuration>

You need to add reference for lesi.collection and NHibernate
You need to do embeded resource for contact.hbm.xml and hibernate_mysql.cfg.xml

我使用了mysql workbench,在那里我创建了一个新的模式和一个带有id,名字和姓氏的新表。

对于异常没有持久性的解决方案,我忘了在contact.hbm.xml

中提供表名