C# – object references an unsaved transient instance save the transient instance before flushing

cnhibernatenhibernate-mappingorm

i have a self join employees entity class with id,name and ref columns that has relation with it self. i want to create new instance of that and persist it to db.

at first i created an instance of Employee class and named it manager. then i fetched a record from Employee table with these values: Id = 1, Name = "A", RefId = null
and set those values to manager object. after that i created an instance of Employee class again
and set it's properties value like this:
emp.Name = "B", emp.Ref = manager.
finally i persisted it by using base.Add(resource) method. at that time Nhibernate raised the following error:
"object references an unsaved transient instance save the transient instance before flushing".

this is mapping file contents:

<class name="Employee" table="Employee" schema="dbo" optimistic-lock="none" lazy="true">
    <id name="Id" access="property" column="Id">
        <generator class="identity" />
    </id>
    <property name="Name" type="String" column="Name" length="50" />
    <property name="RefId" type="Int64" column="RefId"  insert="false" update="false"/>
    <many-to-one name="Ref" class="Employee" column="RefId" not-null="false" fetch="select" />
 class>

please help me to solve this error.
thx

Best Answer

Let's say Entity 1 is the existing record in the database, and Entity 2 is the new record that you are trying to create that has a reference to Entity 1.

Hibernate is telling you that the new entity (entity 2) you are saving has a reference to entity 1 (the one from the database), and that entity 1 has unsaved changes that must be saved before it can save entity 2. The easiest thing to do is save entity 1 first, then save entity 2. But, I think the real issue is how you are getting an instance of Entity1.

You say that you create and instance of employee, then name it manager, then fetch a record from the employee table. If you are trying to update the existing record from the table, why don't you fetch the entity first, then edit it? Why are you instantiating an object at all? The other thing I wasn't sure about was whether the relationship between the objects was bi-directional. That is, Entity 1 has an FK to Entity 2 AND ALSO Entity 2 has an FK to Entity 1. If this is the case, you need to make sure you assign your "Ref" property twice. Entityy1.Ref = Entity2 AND ALSO Entity2.Ref = Entity1.