c# - NHibernate 映射异常。 : NHibernateTesting. 帐户没有持久性

标签 c# .net nhibernate unit-of-work

我只是想开始学习 NHibernate,在使用极其简单的 POCO 进行测试时我已经遇到了问题。我遇到了 No Persister 异常,我的代码如下所示:

账户表:

create table Account
(
    AccountID int primary key identity(1,1),
    AccountName varchar(10),
    CreateDate datetime
)
go

账户类:

public class Account
{
    public virtual int AccountID { get; set; }
    public virtual string AccountName { get; set; }
    public virtual DateTime CreateDate { get; set; }

    public Account()
    {
        AccountID = 0;
        AccountName = "";
        CreateDate = new DateTime();
    }
}

映射文件,Account.hbm.xml(是的,它嵌入到程序集中):

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   namespace="NHibernateTesting" assembly="NHibernateTesting">
  <class name="Account" table="Account">
    <id name="AccountID">
      <generator class="native"/>
    </id>
    <property name="AccountName" />
    <property name="CreateDate" />
  </class>
</hibernate-mapping>

配置文件中的配置部分:

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
      <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
      <property name="connection.connection_string">My connection string</property>

      <mapping assembly="NHibernateTesting" />

    </session-factory>
</hibernate-configuration>

最后,进行调用的代码:

using (var session = NHibernateHelper.GetASession())
{
    using (var tran = session.BeginTransaction())
    {
        var newAccount = new Account();
        newAccount.AccountName = "some name";

        session.Update(newAccount); // Exception thrown here.

        tran.Commit();
    }
}

谁能看出我做错了什么或者为什么我会得到这个异常,我在网上读到这个问题与映射有关,但我就是看不出这个例子有什么问题。

最佳答案

我已经复制了您所展示的所有映射和代码,并且它正在运行。除了:

var newAccount = new Account(); // NEW
...
session.Update(newAccount); // Update throws exception:

NHibernate.StaleStateException: Batch update returned unexpected row count from update; actual row count: 0; expected: 1

必须通过以下方式保存新对象:session.Save(newAccount);

当您说映射文件被标记为嵌入资源时……很难说到底是哪里出了问题。请尝试仔细点击此链接(并重新检查您的项目),关于 No persister 异常的非常好的经验链:

关于c# - NHibernate 映射异常。 : NHibernateTesting. 帐户没有持久性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14369924/

相关文章:

c# - 需要从 C# 中的分隔符中提取字符串

c# - 需要以相同方式处理的多种方法

c# - 使用标准Window 与wxWidgets 一起绘制成?

.net - nhibernate 和虚拟类属性?

c# - 使用 C# 将证书从 LocalComputer 复制到 CurrentUser

javascript - 使用C#将函数序列化为json中的参数

c# - 如何将这些代码更改为 C# 样式?

c# - 我如何在 NHibernate 中执行反向 LIKE 查询?

linq - 当通过相关表查找时,NHibernate 查询抛出异常

nhibernate - 多对多和HQL批量删除