将流畅的 nhibernate 配置的 DateTime 重新水化为 Kind Utc 而不是 Unspecified [英] Rehydrating fluent nhibernate configured DateTime as Kind Utc rather than Unspecified

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

问题描述

有没有办法在流畅的 nhibernate 中映射 DateTime 以在 DateTime.Kind 设置为 Utc 而不是未指定的情况下重新水合我的实体?我目前坚持使用 Utc 的 DateTime,但返回的 Kind 总是未指定,浪费了我的时间.

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.

推荐答案

这不是 fluent 特有的,而是 NHibernate 映射的基础.我们使用拦截器来指定 Kind.它类似于在这篇博文中的方法 列出了几个替代方案.还有一个 建议的补丁 (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 而不是 Unspecified的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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