Reputation: 5022
I have mapping for A and B classes, where 'one' side is A and 'many' side is B. B references A where foreign key is not nullable. Mapping of A set as Cascade.Delete() for B with FluentNH. When I try to delete A, NHibernate tries to update B and set foreign key to null. So error happens as foreign key is not nullable.
What should I do? Make the foreign key nullable?
EDIT: When I set the foreign key to nullable it works. But is this the right way to go?
Upvotes: 2
Views: 2743
Reputation: 5644
This is because NHibernate attempts to set the foreign key column on the records to null, however since you do not allow nulls in that column, database server throws the error. Try to use .Cascade.AllDeleteOrphan() instead of Cascade.Delete():
In the A mapping class:
HasMany(x => x.B)
.Inverse()
.Cascade.AllDeleteOrphan()
.KeyColumn("foreignKeyID");
Upvotes: 1
Reputation: 11234
Another solution I came across is the following:
HasMany(a => a.B).Cascade.AllDeleteOrphan().Inverse();
You need DeleteOrphan if you want a.B.Clear() to delete all the B's.
EDIT: As you are only cascading delete, here it is for just delete:
HasMany(a => a.B).Cascade.Delete().Inverse();
The inverse attribute is saying that for the relationship from A to B, it is the inverse of A (i.e. B) that owns the relationship (it has the FK in the database). You can read more about inverse Inverse Attribute in NHibernate
Upvotes: 4
Reputation: 722
It's difficult to answer this without item context.
In the problem domain, is it valid to have a B which doesn't have an A?
If so, the foreign key could be nullable.
If not, you need to find a way to delete all the Bs when it's parent A is deleted.
Upvotes: 0