Emad Al-Ashi’s Blog

August 22, 2008

NHibernate Inverse attribute

Filed under: Development, NHibernate — Tags: , , , — eashi @ 5:22 pm

I had to read documentation, articles, many blog entries and go into discussions with colleagues… all to get the root of this ambiguous attribute of NHibernate, it is trickey!
This blog entry is another trial to explain the attribute, but with taking one more detailed step into the explanation.

NHibernate is meant to persist objects as well as to manage their relations to each other, lets take a look at the following example of Parent and Child classes:

public class Parent

    {

        public virtual int Id { get; set; }

        public virtual string Name { get; set; }

        public virtual IList<Child> MyChildren { get; set; }

    }

    public class Child

    {

        public virtual int Id { get; set; }

        public virtual string Name { get; set; }

        public virtual Parent MyParent { get; set; }

and we have corresponding tables to these two classes like the following:

Parent

Child

(note 1: as we are proceeding that there is no Null constraint on the ParentId foreign key in the Child Table)
Finally, we check the interesting part of the mapping files:

  1. Parent:

    <bag name=MyChildren table=Child cascade=all>

          <key column=ParentId/>

          <one-to-many class=Child/>

  2. Child:

    <many-to-one name=MyParent class=Parent >

          <column name=ParentId/>

        </many-to-one>

(note 2: all what the cascade=”all” attribute in the MyChildren bag does is that when ever you save the Parent, all the Child objects in the MyChildren collection are forced to be saved as well; and we are only talking about the Save operation; not interfering or changing any of the values of the Child properties)

Now if we execute the following code:

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

            Child ch = new Child();

            ch.Name = “Emad”;

            par.MyChildren.Add(ch);

            Session.Save(par);

As you may expect, both objects “par” and “ch” will be saved due to note 2 we mentioned above, but the surprise is that when you check the values in the database, you will see that the ParentId field was set as well although we didn’t set it explecitly in the code!

dbValues

The reason is that there is a hidden attribute called “Inverse” in the bag part of the Parent map file whose default value is “false”; when this attribute is set to false like the default value, then the Parent says: “Oh, so it is my responsibility to maintain the relationship with my child objects, ok then when ever a child is added to my collection, when I am saved…I will perform an update SQL statement to their foreign key to point at me”

So when the Save is called, the “par” object is saved, and the “ch” is inserted because calling Session.Save(object) when the object is new it will be inserted.  And after all that happens, an explicit update SQL statement will be executed to update all the child objects to set the foreign key ParentId to the par object Id.

This goes all fine in our case, only due to note 1 (scroll up again); we don’t have an Null constraint on the foreign key ParentId, so the Insert statement is excuted without exceptions, but in most cases in the world, DBA do put this constraint, by that we will get a “cannot insert Null value in ParentId” exception!

The solution is to set the Inverse attribute to “true”, which means that the Parent will NOT updated the Child objects foreign key, it will only call Session.Save(ch) due to the cascade attribute, so the result will be like the record 6:

dbValues2

But then how to solve this problem?! we want to set the value of ParentId AND be able to preserve the Null constraint; so we need to set the MyParent property of the Child to the Parent “par” like line 4:

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

    2             Child ch = new Child();

    3             ch.Name = “Emad”;

    4             ch.MyParent = par;

    5             par.MyChildren.Add(ch);

    6             Session.Save(par);

and to make it graceful, we can create custom collection for the Children and in the Add method of the collection we set the passed Child objects property MyParent to the parent.

You can download the code sample here.

I hope this is detailed enough to explain what the Inverse attribute exactly is, how to go about the Null exception, and to understand that the attributes “Inverse” and “cascade” are different things.

Advertisements

6 Comments »

  1. Great article !

    It’s the first page where I found useful description of an inverse attribute 😉

    Comment by Ogon — July 2, 2009 @ 9:51 am

  2. Thanks Ogon, it’s comments like yours that make it a great day. Thanks and glad that this helped 🙂

    Comment by eashi — July 2, 2009 @ 10:54 am

  3. thanks! I’ve been searching for the solution for half a day, and I solved it according to your great solution

    Comment by Pete — November 18, 2010 @ 8:34 am

  4. Hi Emad,

    Great article. I think you’d add inverse=”false” to Parent mapping.

    Quang

    Comment by Quang — March 1, 2012 @ 1:04 pm

  5. I seldom write comments on blogs, but when I do, it’s because the article is great. Simple explanation with simple example that explains everything. Thanks

    Comment by ekimpl — July 2, 2012 @ 10:18 pm

  6. If some one desires expert view regarding running a
    blog after that i propose him/her to pay a visit this blog, Keep up the fastidious work.

    Comment by simply click the next website — April 8, 2013 @ 2:21 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: