Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to determine if entity is transient or detached

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?

like image 644
Lou Avatar asked Feb 18 '23 20:02

Lou


1 Answers

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:

  1. Create and map a Version or Timestamp column - if it's null, NHibernate will know it needs to persist the entity, or

  2. 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.

like image 112
Lou Avatar answered Apr 10 '23 15:04

Lou