Search code examples
hibernatenhibernatefluent-nhibernateforeign-keysnhibernate-mapping

Ignoring soft foreign keys when referenced row no longer exists


I’m presently working with a NHibernate application that contains table A that once had a foreign key reference to another related table B. This constraint has since been purposely removed as items in B may be deleted out of my control by a secondary application.

Though the constraint is now gone the reference from A to B can still be considered useful if the row in B still exists, otherwise it may be treated a null.

If a row is deleted from B that is referenced by A, quite rightly, an exception is thrown stating that "No row with the given identifier exists".

Is there a way to fluently (or otherwise avoiding explicit queries/joins) to have the object reference return null by the application in the case of a reference from A no longer existing in B, but returning the object as described by B if the reference is valid?

The current unidirectional fluent mapping (treated as a foreign key reference) is rather straight forward looking like

...
References(a => a.b_ref, "b_id");
...

Solution

  • The reference can be ignored and treated as null when not found by updating the fluent mapping to look like

    ...
    References(a => a.b_ref, "b_id").NotFound.Ignore();
    ...
    

    Sometimes it's just a matter of stumbling into the right keyword via Google.