tags:

views:

1438

answers:

2

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

Anyone can shed some lights on this?

+9  A: 

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; 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.

Frederik Gheysels
This explains everything just to add owner is one that has foreign key in table
Brijesh Mishra
http://tadtech.blogspot.com/2007/02/hibernate-when-is-inversetrue-and-when.html
Quintin Par
In my opinion this is really bad terminology. Why not mark the ownership rather than the 'inverse'?!
UpTheCreek
By the way, don't you mean: "Owner = inverse=false; NON-Owner = inverse=true" ?
UpTheCreek
+3  A: 

In addition to the answer above, and according to my understanding, you need to persist the foreign key value in the collection manually, that is if you don't want the extra update statement:

Parent par = Session.Get<Parent>(8);

Child ch = new Child();
ch.Name = “Emad”;

//set the parent foreign key manually
ch.MyParent = par;

par.MyChildren.Add(ch);
Session.Save(par);

for further explanation of the inverse attribute, check the following post:

http://www.emadashi.com/index.php/2008/08/nhibernate-inverse-attribute/

Emad Alashi