Thursday, June 26, 2014

Foreign Key Constraint vs Nhibernate

If you have worked extensively on nhibernate then you will understand the caveat it carries at time of implementation. One of the case is with foreign key constraint for one to many relationship in which it fails to insert rows for child as it always sends foreign key column value zero and when it tries to apply this it into constraint-data integrity conflicts.

Most of the solution suggests:-
1. Apply Inverse =true
2. Apply Cascade all

So on..

But all this solution doesn't work.

When one remove foreign key constraint it works absolutely fine. What it does under the hood?

1. It first insert the parent table enteries.
2. It then insert the child table enteries but keep the foreign key column value as zero
it tries to apply select scope_identity but it return null.
3. Then there are two update on parent and child table where it just update foreign key column with actual values.

The above step is tricky to understand but can be evident in sql profiler log.

Workaround- You can keep the foreign key but can disabled constraint( Disabled Constraint does not mean removing constraint) It still satisfy DDL best practice.

Post a Comment