Ayende @ Rahien

Hi!
My name is Oren Eini
Founder of Hibernating Rhinos LTD and RavenDB.
You can reach me by phone or email:

ayende@ayende.com

+972 52-548-6969

, @ Q c

Posts: 5,953 | Comments: 44,409

filter by tags archive

Handling nullable datetime in NHibernate : The Interceptor


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.


Comments

qsjjleja

qsjjleja

Comment preview

Comments have been closed on this topic.

FUTURE POSTS

No future posts left, oh my!

RECENT SERIES

  1. The RavenDB Comic Strip (3):
    28 May 2015 - Part III – High availability & sleeping soundly
  2. Special Offer (2):
    27 May 2015 - 29% discount for all our products
  3. RavenDB Sharding (3):
    22 May 2015 - Adding a new shard to an existing cluster, splitting the shard
  4. Challenge (45):
    28 Apr 2015 - What is the meaning of this change?
  5. Interview question (2):
    30 Mar 2015 - fix the index
View all series

Syndication

Main feed Feed Stats
Comments feed   Comments Feed Stats