我只是想开始学习NHibernate,并且在使用极其简单的POCO进行测试时,我已经遇到了问题。我得到No Persister异常,这是我的代码:
Account
表:
create table Account
(
AccountID int primary key identity(1,1),
AccountName varchar(10),
CreateDate datetime
)
go
Account
上课:
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();
}
}
任何人都可以看到我做错了什么或为什么我会得到这个例外,我在网上看到这个问题与映射有关,但我只是看不出这个例子中的错误。
答案 0 :(得分:3)
我已经重现了您展示的所有映射和代码,并且它正在运行。不同的是:
var newAccount = new Account(); // NEW
...
session.Update(newAccount); // Update throws exception:
NHibernate.StaleStateException:批量更新返回意外行 从更新开始计算;实际行数:0;预期:1
必须通过以下方式保存新对象:session.Save(newAccount);
当你说,映射文件被标记为嵌入式资源时...很难说究竟是什么错误。请尝试仔细关注此链接(并重新检查您的项目),以及关于 No persister 的非常好的经验链:
答案 1 :(得分:2)
由于映射配置无效而发生此错误。您应该检查您为会话工厂设置的.Mappings的位置。基本上在项目中搜索“.Mappings(”并确保在下面的行中指定了正确的实体类。
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<YourEntityClassName>())