0
votes

Why do I need to add relationships for child and parent?

Child child = Session.Get(1);
Parent parent = Session.Load(1);
parent.Children.Add(child);
child.Parent = parent;

It works perfectly without parent.Children.Add(child) if use inverse=true and I don't need Children collection in current session (session per web request). Do you always add relationship for child and parent?

2

2 Answers

2
votes

Setting child.Parent = parent is enough to persist the relationship.

However, if you don't add the child to the collection, you won't be able to take advantage of cascading, so you'll have to persist the child explicitly.

Also, if you don't set one of the sides, you'll have an inconsistent memory model (because the child won't be added to the collection unless you reload it).

2
votes

I hope I understood you correctly.

class Parent { List Children {get;set;} class Child { Parent Parent {get;set;}

ANS1. In this scenario Inverse tells the nhibernate framework to leave the control mechanism of [Parent-Child] relationship to the Child (it is mostly about which object is responsible for Deleting/Updating the Child). With Inverse attribute on Children property Child is responsible for itself, otherwise Parent is responsible for deleting a Child.

ANS2. You do not need both properties (Children, Parent) in most cases (you need them if you specify inverse=true on Children). It only depends on the functionality you want to get.

Does this briefly answer your question?