NHibernate configuration for uni-directional one-to-many relation
Solution 1:
NH3 and above allow to correct save entities in case of uni-directional one-to-many mapping without annoying save null
-save
-update
cycle, if you set both not-null="true"
on <key> and inverse="false"
on <one-to-many>
FluentNHibernate code snippet for that:
public class MasterMap : ClassMap<Master>
{
public MasterMap()
{
Id(x => x.MasterId);
Map(x => x.Name);
HasMany(x => x.Details)
.Not.Inverse() //these options are very
.Not.KeyNullable() //important and work only if set together
.Not.KeyUpdate() //to prevent double update
.Cascade.All();
}
}
Solution 2:
You can't. To quote the link from my answer on the other question you linked to:
Very Important Note: If the
<key>
column of a<one-to-many>
association is declared NOT NULL, NHibernate may cause constraint violations when it creates or updates the association. To prevent this problem, you must use a bidirectional association with the many valued end (the set or bag) marked asinverse="true"
. See the discussion of bidirectional associations later in this chapter.
Edit: as Hazzik has rightly pointed out, this has changed in NHibernate 3 and above. The docs sadly haven't been updated, so here's Hazzik:
[If you] set
inverse="false"
andnot-null
on<key>
, NH3 and above will perform only two inserts insead of insert-insert-update.
Solution 3:
The reason NHibernate does it this way is because:
When it saves the detail it only knows about the stuff the detail knows about. So any master references which happen in the background are ignored.
Only when the master is saved it sees the relation and updates the elements of the collection with the id of the master.
Which is from an object oriented point of view logical. However from a saving point-of-view is slightly less logical. I suppose you can always file a bug report, or look if it might have been filed already and ask them to change it. But I suppose they have their specific (design/domain) reasons.