views:

137

answers:

1

I have a table in a MySql database with a datetime field. This is mapped to my domain object in an hbm.xml file with a property similar to the following:

<property name="StartDate" column="datStartDate" not-null="true" type="datetime"/>

This all works fine, except MySql doesn't store the millisecond portion of the DateTime field. I don't mind, however, I would like the domain object to be updated to have the exact value that is stored in the database. I'd like to be able to do this within the same session that I use to save the domain object.

Is this possible?

A: 

A simple way is to do session.Refresh(entity), but this results in an extra query.

In Interceptor would work, just seems very heavy.

http://www.nhforge.org/doc/nh/en/index.html#objectstate-interceptors (11.1)

You'd want something like:

public override bool OnFlushDirty(object entity, 
                                  object id, 
         object[] currentState,
         object[] previousState, 
         string[] propertyNames,
         IType[] types) 
{
    if(entity is DomainObjectICareAbout)
        for ( int i=0; i < propertyNames.Length; i++ ) {
            if ( currentState[i] is DateTime ) {
                DateTime dt = (DateTime)currentState[i];
                dt = dt.AddMilliseconds(-1 * dt.Millisecond);
                return true;
            }
        }
    }
    return false;
}

Same kind of thing for OnSave().

It would probably be nicer to do this in a Custom IUserType, but I'm not sure user types expose the ability to do this?

Like for a IUserType:

public void NullSafeSet(System.Data.IDbCommand cmd, object value, int index)
{
    DateTime dt = (DateTime)value;
    dt = dt.AddMilliseconds(-1 * dt.Millisecond);
    NHibernateUtil.DateTime.NullSafeSet(cmd, dt, index);
}

I dunno... I'm not sure the best answer. Just giving ideas. There might be a better way!

eyston
I think I'm going to use session.Refresh for now, even though it hits the database again. This has already proved useful: I found that I wasn't setting the charset in the connection string, so I lost unicode characters ;).
Andrew
Yah, re-reading your question (the part about keeping the same session) it looks like Session.Refresh() was the right answer.
eyston