Inverse Attribute in NHibernate

Graviton picture Graviton · Apr 3, 2009 · Viewed 35.8k times · Source

How do I use the Inverse Attribute? If I am not mistaken, for one to many relationships the inverse attribute must be set to true. For many-to-many relationships, one of the entity class inverse attributes must be set to true and another set to false.

Anyone can shed some lights on this?

Answer

Frederik Gheysels picture Frederik Gheysels · Apr 3, 2009

The inverse attribute must not be set to true ...

You use the inverse attribute to specify the 'owner' of the association. (An association can have only one owner, so one end has to be set to inverse, the other has to be set to 'non inverse'). (Owner: inverse=false; Non-owner: inverse=true)

In a one-to-many association, if you do not mark the collection as the inverse end, then NHibernate will perform an additional UPDATE. In fact, in this case, NHibernate will first insert the entity that is contained in the collection, if necessary insert the entity that owns the collection, and afterwards, updates the 'collection entity', so that the foreign key is set and the association is made. (Note that this also means that the foreign key in your DB should be nullable).

When you mark the collection end as 'inverse', then NHibernate will first persist the entity that 'owns' the collection, and will persist the entities that are in the collection afterwards, avoiding an additional UPDATE statement.

So, in an bi-directional association, you always have one inverse end.