How To: NHibernate Parent/Child Relationships

So you’re trying to setup a Parent/Child relationship using NHibernate. This is easy enough when you allow the foreign keys to be null in your database. Of course this is not desirable for data integrity so you disallow nulls. Now NHibernate is pissed because it wants to insert the child row first then update it with the parent id.

You can fix this by setting up a bi-directional relationship. Simply put, try the following.

In your Parent.hbm.xml add:

<set name="Children" inverse="true" cascade="all-delete-orphan">
 <key column="parent_id"/>
 <one-to-many class="Child"/>

In your Child.hbm.xml add:

<many-to-one name="Parent" column="parent_id" not-null="true"/>

Now you need to make sure you update the Child class to “know about” the Parent. To make this easy add this method to your Parent class:

public void AddChild(Child c)
 c.Parent = this;

Now we can do this:

Parent p = new Parent();
Child c = new Child();

That’s the tall and skinny of it. To really understand this concept check out Chapter 16 of the NHibernate Reference Documentation.