Question

I have parent table "Parent" with column "SpokenlanguageId", "WrittenlanguageId". These two columns are referenced by column "languageid" in child table (both Parent table columns are referred by same child table column).

In parent table hbm file, I have included many to one relationship on parent table columns (SpokenlanguageId, WrittenlanguageId) with cascade = "None" my scenario would be to insert and update data only in parent table not on child table as it a lookup table. I get the following error with above settings being set on my hbm file

NHibernate.TransientObjectException

object references an unsaved transient instance - save the transient instance before flushing or set cascade action for the property to something that would make it autosave.

I got above error while flushing the nhibernate session.

Was it helpful?

Solution

Based on more information in the comments, there are more details

parent class:

Language SpokLanguages { get; set; } 
Language WrittenLanguages { get; set; } 

parent.hbm.xml file:

<many-to-one name="SpokLanguages" class="Language" 
  column="SpokenLanguageID" unique="true" cascade="none" /> 
<many-to-one name="WrittenLanguages" class="Language" 
  column="WrittenLanguageID" unique="true" cascade="none" /> 

And this was the way how to assign property:

SpokLanguages    = new Language() { SpokenLanguageID = 5, };
WrittenLanguages = new Language() { WrittenLanguageID = 6, };

Which was almost correct, but what we need is to assign the ID of Language

parent.SpokLanguages    = new Language() { ID = 5, };
parent.WrittenLanguages = new Language() { ID = 6, };

because this ID property is what is mapped here

the column, in the Paren table will contain the ID of the Language. The essence of the mapping <many-to-one> is in fact, that NHibernate is trying to put together the information in the Parent table... with the ID of the Language. The element mapped in Langauge as id

<class name="Language" ... 
 <id name="ID"

is what we need. If this is missing, entity seems to be transient. And that's why NHibernate blames.

EXTEND:

The more appropriate solution would be to load the instances of selected Languages from DB and assign them. It could be done even with some trick, the Load method. Please, read:

it could look like this

parent.SpokLanguages    = session.Load<Language>(5)
parent.WrittenLanguages = session.Load<Language>(6)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top