2

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?

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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"); 

1 Comment

I think your solution will work, but because of the Inverse(), not AllDeleteOrphan(). I tried it with Cascade.Delete() and it works.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.