Search code examples
c#.netormfluent-nhibernate

What is the Use of Inverse() in Nhibernate


In my project i see the below code where is Inverse() is used I want to understand what is use of it and parent child relationship works with and without inverse

public CityMap()
{
    Table("Cities");

    HasMany<CityName>(x => x.CityNames)
        .KeyColumn("CityID")
        .Inverse()
        .Cascade.All()
        .Cascade.AllDeleteOrphan();
}

can someone share the how inverse effects the parent and child relationship, and what exactly it does and also while deleting I want to understand the order of query execution


Solution

  • Assuming we have a simple relation of a parental entity with a collection of child-entities

    {
       id  : <set by NHibernate>,
       name: "Parent",
       children: {
          {
             id        : <set by NHibernate>,
             parentId  : <set by NHibernate>,
             name      : "Child A",
          },
                    {
             id        : <set by NHibernate>,
             parentId  : <set by NHibernate>,
             name      : "Child B",
          }
       }
    }
    

    By using .Inverse(), NHibernate would store the entites to your database with the following steps:

    1. Insert the parent (<= parent Id is now known)
    2. Insert the children (=> including their foreign key to parent, since the parents Id is known)

    Without using .Inverse() these steps change:

    1. Insert children (=> excluding their foreign key to parent as it is not known yet)
    2. Insert parent (<= parent Id is now known)
    3. Update each child, setting the parents Id as foreign key

    Note the additional Update(s) in step 3 that can be saved by using .Inverse(). Without the use of .Inverse() the foreign key on the children also needs to be configured as nullable since at the time of their insert the foreign-key Id is not known yet (step 1). The nullable foreign key is what (at least theoretically) opens the door for foreign-key violations since now a child may be inserted without a parent-reference being strictly necessary.

    Hope this gives you an idea!