tags:

views:

68

answers:

0

I'm trying to use nhibernate with a legacy database that has 'evolved' over the past decade or so. As you can imagine, it has a lot of crud in it, specifically, some obsolete columns. To make things worse, a lot of these obsolete columns have 'NOT-NULL' constraints, so I can't just ignore them when trying to insert records into these respective tables.

I'm looking for a way to dynamically insert the necessary column names and values for obsolete columns without having to pollute my domain model with useless private properties. Unfortunately in my scenario, modifying the database schema is out of question as there are other existing applications which still rely on them. From my research, it seems like defining an OnSave Interceptor is the way to go.

I've already seen these existing SO questions:

http://stackoverflow.com/questions/579885/unmapped-columns-in-nhibernate http://stackoverflow.com/questions/824316/nhibernate-add-unmapped-column-in-interceptor

But working code samples in both questions are non-existent (at least, I couldn't get them to work). Here's what I've tried:

public class DefaultValueInterceptor : EmptyInterceptor
    {
        public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types)
        {
            if (entity is EquipmentItem)
            {

                //manaully add legacy columns
                var pnList = propertyNames.ToList();
                pnList.Add("LegacyColumn");
                propertyNames = pnList.ToArray();

                var stateList = state.ToList();
                stateList.Add(false);
                state = stateList.ToArray();

                var typeList = types.ToList();
                typeList.Add(NHibernateUtil.Boolean);
                types = typeList.ToArray();

                return true;
            }
            return base.OnSave(entity, id, state, propertyNames, types);
        }
    }

When I run this, however, the resulting query doesn't include the column I've dynamically added in the interceptor, and I still get the "Cannot insert the value NULL into column x" error.

Any thoughts on what I'm doing wrong? Thanks for the help.