代码之家  ›  专栏  ›  技术社区  ›  Lisa

Nhibernate更新不会持久化对数据库的更改

  •  1
  • Lisa  · 技术社区  · 15 年前

    我在使用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>
    
    2 回复  |  直到 14 年前
        1
  •  2
  •   rebelliard    15 年前

    你错过了 Flush :

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

    更多: Committing the database transaction

        2
  •  1
  •   Lisa    15 年前

    <class name="RepositoryDto" table="Repository" mutable="false"> 
    

    更改为

    <class name="RepositoryDto" table="Repository" mutable="true"> <!-- or just delete mutable to use default of true -->