1

我在获取使用 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>
4

2 回答 2

2

你错过了Flush

// etc...
nhbSession.Update(existingRepository);
nhbSession.Flush();
nhbSession.Transaction.Commit();
// etc...

更多:提交数据库事务

于 2010-10-07T02:46:33.933 回答
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 映射表示它不是可变的,因此您不能在此对象上调用更新”形式的异常会很好!

于 2010-10-07T03:46:00.440 回答