在尝试使用手动生成的 ID 持久化实体时,我在 NHibernate (v3.3) 中遇到了一个奇怪的错误:
Unable to determine if {Entity} with assigned identifier {Id} is transient or detached; querying the database. Use explicit Save() or Update() in session to prevent this.
但问题是,我使用的是
Save
而不是 SaveOrUpdate
.可能是什么问题呢?
最佳答案
事实证明,我的问题实际上是在保存父实体时发生的,其中包含一对多关系中的子实体:
<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 ,其中有两个很好的建议:
关于.net - 无法确定实体是暂时的还是分离的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12917217/