I have an employee entry screen for a new employee, that upon submit gets intercepted by an employee model binder. An employee has a "business unit" and an "override business unit". The override business unit was a recently added and is the cause of my problems.
Here is a partial employee mapping:
<class name="Employee" table="Employee">
<id name="Id" column="id">
<generator class="native" />
</id>
...
<many-to-one name="BusinessUnit" class="BusinessUnit" column="businessUnitId" />
<many-to-one name="OverrideBusinessUnit" class="BusinessUnit" column="overrideBusinessUnitId" not-null="false" />
...
</class>
Here is the business unit mapping:
<class name="BusinessUnit" table="BusinessUnit" lazy="true">
<id name="Id" column="id">
<generator class="native" />
</id>
<property name="Description" column="description"/>
<many-to-one name="guidelineApprover" class="Employee" column="guidelineApproverId" cascade="none" fetch="join" access="field" />
<many-to-one name="increaseApprover" class="Employee" column="increaseApproverId" cascade="none" fetch="join" access="field" />
</class>
In the employee model binder after submitting the form, I am using NHibernate to get both the business unit and the override business unit from the database. This is the code:
Fetching the business unit from the database in the model binder:
string attemptedBusinessUnitId = valueProvider.GetValue(key).AttemptedValue;
Int32.TryParse(attemptedBusinessUnitId, out businessUnitId);
employee.BusinessUnit = businessUnitRepository.Get(businessUnitId);
modelState.SetModelValue(key, valueProvider.GetValue(key));
Fetching the override business unit from the database in the model binder:
string attemptedOverrideBusinessUnitId = valueProvider.GetValue(key).AttemptedValue;
Int32.TryParse(attemptedOverrideBusinessUnitId, out overrideBusinessUnitId);
employee.OverrideBusinessUnit = businessUnitRepository.Get(overrideBusinessUnitId);
modelState.SetModelValue(key, valueProvider.GetValue(key));
My current fetch mode is set to "commit". My issue is that I started to get the following error after I added the "override business unit" many-to-one and I attempt to execute employeeRepository.Save(employee):
object references an unsaved transient instance - save the transient instance before flushing.
Type: BusinessUnit, Entity: BusinessUnit
If I set the cascade="all" on this field, I just get another similar exception but about needing to save the transient instance of type Employee, entity EmployeeEmpty. Can anyone tell me by looking at the code snippets how I can avoid this exception (preferably without involving cascade)?
Edit:
employeeRepository.Save(employee) just calls session.SaveOrUpdate(employee). So all I am trying to do is to save the employee after assigning to it, the two business unit fields that I retrieved from the database.