Handling nullable datetime in NHibernate : The Interceptor

time to read 10 min | 1814 words

System.DateTime is a value type, and as such, cannot be null. The default value for DateTime in .Net is DateTime.MinValue, which equals to 01/01/001 00:00. The problem is that SQL Server's dates start at 1753, or there about.

This is usualy solved in .Net 2.0 using Nullable<DateTime> (or DateTime? in C#), but my "entities" are messages to web services, and are generated from WSDL, so they lacked this nice feature. I also didn't realize that some of the DateTime values were nullable until pretty late into the game.

After a lot of head scratching, I came up with this solution, which utilizes NHibernate's IInterceptor capabilities. The interceptor allows to get the raw data before it is loaded and after it is saved, and interfer with it. Using that, I got this DefaultDateToNullInterceptor:

public bool OnFlushDirty(

    object entity, object id, object[] currentState, object[] previousState, string[] propertyNames,

    IType[] types)

{

    MinValueToNull(currentState, types);

    return true;

}

 

public bool OnSave(object entity, object id, object[] state, string[] propertyNames, IType[] types)

{

    MinValueToNull(state, types);

    return true;

}

The OnSave() and OnFlushDirty() methods are called before the values are saved or updated (respectively). The MinValueToNull() method is very simple, it replace all instances of DateTime.MinValue with null, like this:

private static void MinValueToNull(object[] state, IType[] types)

{

    int index = 0;

    foreach (IType type in types)

    {

        if(type.ReturnedClass == typeof(DateTime) &&

           DateTime.MinValue .Equals(state[index] ))

        {

            state[index] = null;

        }

          

        index+=1 ;

    }

}

All that was left was openning the session with the interceptor, and I was set.