IWr*_*pps 5 .net c# nhibernate unit-of-work
我只是想开始学习 NHibernate,在使用极其简单的 POCO 进行测试时我已经遇到了问题。我收到 No Persister 异常,这是我的代码:
Account桌子:
create table Account
(
AccountID int primary key identity(1,1),
AccountName varchar(10),
CreateDate datetime
)
go
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
映射文件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>
Run Code Online (Sandbox Code Playgroud)
配置文件中的配置部分:
<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>
Run Code Online (Sandbox Code Playgroud)
最后,调用代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以看到我做错了什么或者为什么我会得到这个异常,我在网上读到这个问题与映射有关,但我只是看不出这个例子中有什么问题。
我已经复制了您所显示的所有映射和代码,并且它正在工作。除了:
var newAccount = new Account(); // NEW
...
session.Update(newAccount); // Update throws exception:
Run Code Online (Sandbox Code Playgroud)
NHibernate.StaleStateException:批量更新从更新中返回意外的行数;实际行数:0;预计:1
新对象必须通过以下方式保存:session.Save(newAccount);
当您说映射文件被标记为嵌入资源时...很难说到底出了什么问题。请尝试仔细关注此链接(并重新检查您的项目),其中有关于No persister异常的非常好的经验链: