【问题标题】:Unable to determine if entity is transient or detached无法确定实体是暂时的还是分离的
【发布时间】:2012-10-16 14:38:30
【问题描述】:

在尝试使用手动生成的 ID 持久化实体时,我在 NHibernate (v3.3) 中遇到了一个奇怪的错误:

无法确定具有分配标识符 {Id} 的 {Entity} 是暂时的还是分离的;查询数据库。 在会话中使用显式 Save() 或 Update() 来防止这种情况发生。

但问题是,我使用Save 而不是SaveOrUpdate。可能是什么问题?

【问题讨论】:

  • 您是否有任何抽象层位于 NHibernate 之上?你有任何版本/时间戳列吗?你能发布你的映射和代码吗?
  • 最后我意识到问题出在保存父实体时级联子实体,SO上有一个答案,它解释了解决该问题的可能方法。我已经修复了它,但还没有时间发布我的发现。
  • 您介意链接解决您问题的答案吗?
  • @Firo:当然,正如我所提到的,我很忙,我一会儿就做。

标签: .net nhibernate transient


【解决方案1】:

事实证明,我的问题实际上是在保存父实体时发生的,其中包含一对多关系中的子实体:

<class xmlns="urn:nhibernate-mapping-2.2" name="ParentTable" table="ParentTable">

    <id name="ManuallyAssignedId">
      <generator class="assigned" />
    </id>

    <!- child table also has a manually assigned id -->
    <bag cascade="all" inverse="true" name="ChildTable">
      <key>
        <column name="ParentTable_id"/>
      </key>
      <one-to-many class="ChildTable" />
    </bag>

</class>  

换句话说,在父实体上调用 Save 会导致在子实体上出现 SaveOrUpdate,这是 NHibernate 所抱怨的。

当我意识到这一点时,我很快找到了这个 StackOverflow 线程:How to save a child with assigned id in nhibernate,它有两个很棒的建议:

  1. Create and map a Version or Timestamp column - 如果它为 null,NHibernate 将知道它需要持久化实体,或者

  2. Attach a custom Interceptor to a session (or session factory) 并使用自定义私有字段来跟踪实体是否需要持久化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    相关资源
    最近更新 更多