补充流畅的nhibernate配置DateTime为Kind Utc而不是未指定 [英] Rehydrating fluent nhibernate configured DateTime as Kind Utc rather than Unspecified

查看:203
本文介绍了补充流畅的nhibernate配置DateTime为Kind Utc而不是未指定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在流畅的nhibernate中有没有办法映射一个DateTime来将DateTime.Kind设置为Utc而不是未指定的实体?我目前正在坚持使用Utc的DateTime,但回来的时候总是没有指定,扔掉我的时间。

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.

推荐答案

这不是流畅的,而是NHibernate映射的基础。我们使用拦截器来指定种类。它类似于此博客文章列出了几种替代方案。还有一个提出的补丁(NH-1135),用于本地处理UtcDateTime和LocalDateTime。我鼓励你投票。

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);
        }
    }
}

这篇关于补充流畅的nhibernate配置DateTime为Kind Utc而不是未指定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆