views:

369

answers:

3

I've set up a one-to-many association in NHibernate:

Parent (1 -> ∞) Child

The problem I now face is that when I set Child.Parent, the Parent.Children collection doesn't automatically contain the new Child. Similarly, when I add a Child to the Parent.Children collection, the Child.Parent property is still null. I could write some code in the property setters to achieve this, but is there a standard approach to this sort of thing?

Thanks

A: 

When you set Child.Parent, you also have to add the Child to the Parent.Children, NHibernate (.net for that matter) can't know that you set the parent.

sirrocco
A: 

Thanks. Clearly .net can't do this for me automatically, but was just wondering if there was a best practice for this situation rather then spewing a load of repeated code in the property accessors.

James L
+1  A: 

Do you really want to have this behavior ? Is it really necessary ?

I always make my 'Parent' reference readonly with an internal setter, and I also do not expose the Children collection of the parent as a regular collection. My Parent has a AddChild method, which adds the child to the collection, and sets the Parent property of the child. Next to that, my Parent can return a ReadOnlyCollection of type 'Child'.

Frederik Gheysels