I have Two Table , tableA and tableB.
tableA have column : tabAId, col2, col3 (tabAId primaryKey and Identity column.)
tableB have column : tabAId, name (tabAId is not null)
I have create Bag in hbm file of tableA, to maintain relation ship.
<bag name="tableB" lazy="true" inverse="false"
batch-size="25" cascade="all-delete-orphan">
<key column="tabAId" />
<one-to-many class="tableB" />
</bag>
When I try to update record in tableA it throw exception, where as I have list of child in tableA instance.
[NHibernate.Exceptions.GenericADOException] = {"could not delete collection: [MIHR.Entities.tableA.tableB#21][SQL: UPDATE dbo.tableB SET tabAId = null WHERE tabAId = @p0]"}
InnerException = {"Cannot insert the value NULL into column 'tabAId', table 'SA_MIHR_DEV.dbo.tableB';
column does not allow nulls. UPDATE fails.\r\nThe statement has been terminated."}
There are only two ways how to solve this.
1) do not use inverse="false"
<bag name="tableB" lazy="true" inverse="true" // instead of false
batch-size="25" cascade="all-delete-orphan">
<key column="tabAId" />
<one-to-many class="tableB" />
</bag>
This setting (inverse="true") will instruct NHibernate to directly delete an item from DB.
While using inverse="false"
will in general always lead to:
- UPDATE (with null) == act of removing from collection
- DELETE item == act of cascade
2) make the reference column nullable
That means, that we can leave NHibernate to do UPDATE and DELETE. Because column is now nullable.
These are only two ways how to solve it here.
My preference would be: inverse="true"
To work properly with inverse="true"
we always have to assign both sides of relation in C#. This is a must for Add(), INSERT operation:
Parent parent = new Parent();
Child child = new Child
{
...
Parent = parent,
};
// unless initialized in the Parent type, we can do it here
parent.Children = parent.Children ?? new List<Child>();
parent.Children.Add(child);
// now just parent could be saved
// and NHibernate will do all the cascade as expected
// and because of inverse mapping - the most effective way
session.Save(parent);
As we can see, we have assigned - explicitly - both sides of relationship. This is must to profit from NHibernate inverse mapping. And it is also good practice, because later, when we load data from DB we expect, that NHibernate will take care about setting that for us