我在使用NHibernate检索到的数据对象中进行更改以将其保留回数据库时遇到问题。我没有例外,所以很难知道在哪里看。有什么建议吗?
string name = "somenewname";
string repositoryId = "somerepositoryid";
ISession nhbSession = GetNhbSession(session);
nhbSession.Transaction.Begin();
try
{
RepositoryDto existingRepository = nhbSession.Get<RepositoryDto>(repositoryId);
if (existingRepository == null || existingRepository.TimeDeleted != null)
throw new Exception("Repository does not exist in system or is deleted. Cannot modify.");
existingRepository.Name = name; //works fine up to here as expected; is in DB with old name
nhbSession.Update(existingRepository);
nhbSession.Transaction.Commit();
}
catch (Exception ex)
{
nhbSession.Transaction.Rollback();
throw new Exception("Error modifying repository: " + ex.Message, ex);
}
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="SomeComponent"
namespace="SomeComponent.Repository.DTO" auto-import="true" default-lazy="false">
<class name="RepositoryDto" table="Repository" mutable="false">
<id name="RepositoryId" column="repositoryId" unsaved-value="0">
<generator class="assigned"/>
</id>
<property name="SystemId" column="systemId" not-null="true" />
<property name="TimeCreated" column="timeCreated" not-null="true" />
<property name="TimeDeleted" column="timeDeleted" not-null="false" />
<property name="Name" column="name" not-null="true" />
</class>
</hibernate-mapping>
答案 0 :(得分:2)
您错过了Flush
:
// etc...
nhbSession.Update(existingRepository);
nhbSession.Flush();
nhbSession.Transaction.Commit();
// etc...
答案 1 :(得分:1)
我发现了这个问题。我的RepositoryDto类中有一个流浪的'mutable =“false”',它从我假设的不同类映射的复制和粘贴中删除了剩余的。找到一个非常讨厌的人!!
<class name="RepositoryDto" table="Repository" mutable="false">
更改为
<class name="RepositoryDto" table="Repository" mutable="true"> <!-- or just delete mutable to use default of true -->
来自NHibernate的一个例外形式“RepositoryDto映射表明它不可变,所以你不能在这个对象上调用Update”会很好!