Allow many-to-one using not-null foreign-key while using inverse=false on the one-side

Description

My goal is to control the relation using the set (the one-side, hence the inverse=false), while maintaining the not null property on the foreign key (since I want to make sure there are never any children without parents, so legancy code not using NHibernate can't corrupt my database) while still being able to get the parent from an arbitrary child.

The mapping looks like this:

<class name="Parent">
<id name="Id">
<generator class="identity"/>
</id>
<property name="Name"/>
<set name="Children" inverse="false">
<key column="ParentId" not-null="true" />
<one-to-many class="Child"/>
</set>
</class>

<class name="Child">
<id name="Id">
<generator class="identity"/>
</id>
<many-to-one name="Parent" column="ParentId" />
<property name="Name"/>
</class>

When I try to persist a new Parent object with some children, I get an exception: "not-null property references a null or transient value Model.Child.Parent"

When I'm using not-null="false" instead, it works. But since NHibernate 3, NHibernate inserts the Parent first and the Children afterwards, so there is no need to check the Parent property on the Child for not-null. I even would make this property read-only, since it has more an informative character for code reading/update those classes...

Using MS SQL 2008 R2 and Visual Studio 2012 and .NET 4.0.

Environment

None

Activity

Show:
Alex Zaytsev
March 25, 2018 at 9:07 AM

Moved here.

Details

Assignee

Reporter

Labels

Components

Affects versions

Priority

Who's Looking?

Open Who's Looking?
Created December 6, 2012 at 1:07 PM
Updated March 25, 2018 at 9:07 AM
Who's Looking?