views:

64

answers:

1

Simple question: does it matter which side of a bidirectional many-to-many relationship you set as the inverse in NHibernate? And if so, what are the implications of setting it on one end vs. the other?

Some more clarification: I'm setting both sides of the relationship:

Parent.Children.Add(child);
Child.Parents.Add(parent);

In a case like this, does it matter which side I mark as inverse?

+3  A: 

Yes it matters, changes made only to the inverse end of the association are not persisted

You may check nhibernate documentation for further details. Here you have the link:

http://www.nhforge.org/doc/nh/en/#collections-bidirectional

EDIT

My answer doesn't change with your addition, but I'll try to explain it better :-)

if you set Parent.Children with inverse = true you need to save Child object in order to save the relation. If you ONLY save Parent then the relation won't be saved

if you set Child.Parent with inverse = true you need to save Parent object in order to save the relation. If you ONLY save Child then the relation won't be saved

category.Items.Add(item);  // The category now "knows" about the relationship
item.Categories.Add(category);  // The item now "knows" about the relationship

session.Update(item);    // No effect, nothing will be saved!
session.Update(category);    // The relationship will be saved
Claudio Redi
Whoops, I forgot to clarify. I'm setting both sides of the relationship using `Child.Parent.Add(parent); Parent.Child.Add(child)`. In a case like this, does it really matter which side is set as inverse?
Daniel T.
No, it doesn't from NH's point of view.
Diego Mijelshon
Thanks Diego. Can you write that as an answer? Claudio's answer is good, but doesn't exactly answer my question. In his case, you only have to set one side of the relationship, and that's when it matters which side you set. However, in my case I'm setting both sides, and I was wondering if it mattered in that case which side's inverse.
Daniel T.
@Daniel: I feel like if we were talking about different things :-). The nhibernate link I pasted shows a many-to-many relation with BOTH SIDES SET. I just pasted a piece of code from there.
Claudio Redi
I suppose you're right, Claudio. Marked as the accepted answer :).
Daniel T.