I am getting a weird error in NHibernate (v3.3), when trying to persist an entity with a manually generated ID:
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.
But the problem is, I am using Save
instead of SaveOrUpdate
. What could be the problem?
It turned out that my problem was actually happening while saving the parent entity, containing child entities in a one-to-many relation:
<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>
In other words, a call to Save
on the parent entity caused a SaveOrUpdate
on child entities, which NHibernate was complaining about.
When I realized that, I quickly found this StackOverflow thread: How to save a child with assigned id in nhibernate, which has two great suggestions:
Create and map a Version or Timestamp column - if it's null, NHibernate will know it needs to persist the entity, or
Attach a custom Interceptor to a session (or session factory) and use a custom private field to keep track of whether the entity needs to be persisted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With