Unexpected row count in Nhibernate when deleting parent records with associated child records
-
21-09-2019 - |
Question
I have a parent table, Orders and a child table, [Order Details], I have setup the fluent mappings as -
(In the parent Order class)
HasMany<OrderDetails>
(x => x.Details).KeyColumn("OrderId").Cascade.AllDeleteOrphan().Inverse();
(In the child [Order Details] class)
References(x => x.ParentOrder).Column("OrderId").Not.Nullable().Cascade.None();
I am trying to delete the parent object by calling -
session.Delete(parent);
session.Flush();
this works only when there is only one child record, if there are more than one child records, the children get deleted, but the parent doesn't!!! And I get the dreaded - Unexpected row count error.
I am sure that this is something silly that I am doing, but trawling through the web hasn't turned up anything.
Thanks
Solution
Ok, I figured this out, it was me being stupid, but then the answer might help someone else, so here goes.
The [Order Details] table has a composite key and is linked to the both the [Orders] and [Products] table (Yes, this is the Northwind database that I am working with). For my test, I hadn't mapped my Products table, and had marked up my [Order Details] class with a single primary key, rather than a composite key. So, when Nhibernate deleted rows based on the key, it expects to see only one row being deleted whereas multiple existed on the database. Which is why I was getting the error. Rather clever of Nhibernate.