views:

23

answers:

1

I'm using NHibernate (fluent) to access an old third-party database with a bunch of tables, that are not related in any explicit way. That is a child tables does have parentID columns which contains the primary key of the parent table, but there are no foreign key relations ensuring these relations. Ideally I would like to add some foreign keys, but cannot touch the database schema.

My application works fine, but I would really like impose a referential integrity rule that would prohibit deletion of parent objects if they have children, e.i. something similar 'ON DELETE RESTRICT' but maintained by NHibernate.

Any ideas on how to approach this would be appreciated. Should I look into the OnDelete() method on the IInterceptor interface, or are there other ways to solve this?

Of course any solution will come with a performance penalty, but I can live with that.

A: 

I can't think of a way to do this in NHibernate because it would require that NHibernate have some knowledge of the relationships. I would handle this in code using the sepecification pattern. For example (using a Company object with links to Employee objects):

public class CanDeleteCompanySpecification
{
    bool IsSatisfiedBy(Company candidate)
    {
        // Check for related Employee records by loading collection
        // or using COUNT(*).
        // Return true if there are no related records and the Company can be deleted.
        // Hope that no linked Employee records are created before the delete commits.
    }
}
Jamie Ide