Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rehydrating fluent nhibernate configured DateTime as Kind Utc rather than Unspecified

Is there a way in fluent nhibernate to map a DateTime to rehydrate my entity with DateTime.Kind set to Utc rather than unspecified? I'm currently persisting a DateTime that is Utc, but the Kind coming back is always Unspecified, throwing off my time.

like image 296
Arne Claassen Avatar asked Oct 10 '09 05:10

Arne Claassen


2 Answers

This isn't specific to fluent, but is fundamental to the NHibernate mapping. We use an interceptor to specify the Kind. It is similar to the approach in this blog post which lists a couple alternatives. There is also a proposed patch (NH-1135) for handling UtcDateTime and LocalDateTime natively. I'd encourage you to vote for it.

public class InterceptorBase : EmptyInterceptor
{
    public override bool OnLoad(object entity, object id, object[] state,
        string[] propertyNames, IType[] types)
    {
        ConvertDatabaseDateTimeToUtc(state, types);
        return true;
    }

    private void ConvertDatabaseDateTimeToUtc(object[] state, IList<IType> types)
    {
        for (int i = 0; i < types.Count; i++)
        {
            if (types[i].ReturnedClass != typeof(DateTime))
                continue;

            DateTime? dateTime = state[i] as DateTime?;

            if (!dateTime.HasValue)
                continue;

            if (dateTime.Value.Kind != DateTimeKind.Unspecified)
                continue;

            state[i] = DateTime.SpecifyKind(dateTime.Value, DateTimeKind.Utc);
        }
    }
}
like image 36
g . Avatar answered Sep 22 '22 10:09

g .


As of Nhibernate 3.0, using FluentNHibernate, you can do the following:

Map(x => x.EntryDate).CustomType<UtcDateTimeType>();

No need to use interceptors anymore.

like image 134
David Peden Avatar answered Sep 18 '22 10:09

David Peden