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.
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);
}
}
}
As of Nhibernate 3.0, using FluentNHibernate, you can do the following:
Map(x => x.EntryDate).CustomType<UtcDateTimeType>();
No need to use interceptors anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With