首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NPoco / PetaPoco和Noda时间类型

NPoco / PetaPoco和Noda时间类型
EN

Stack Overflow用户
提问于 2014-01-12 14:32:51
回答 2查看 993关注 0票数 2

我刚刚开始使用NPoco,但到目前为止,我还没有在文档中找到我需要的东西。

例如,假设我有一个字段Created,它是我域中的Instant,但是数据库中的DateTimeOffset设置为UTC。有办法让NPoco转换这些类型吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-01-15 08:04:33

我扩展了Schotime演示的接口,并为几种NodaTime类型构建了它。太大了,不能粘贴在这里,所以这是一个GIST

注意,它不包括ZonedDateTime,它必须序列化到两个不同的字段,所以我不确定NPoco将如何处理这个问题。我也没有包括Period,因为除了varchar没有其他很好的对应类型。

警告:这段代码是完全未经测试的。我只是把我所知道的关于Noda时间转换的内容应用于重写,而另一个答案则说明了这一点。在代码中使用之前,请彻底测试它。

票数 2
EN

Stack Overflow用户

发布于 2014-01-14 03:35:20

这很容易。下面的示例是用来处理PostgreSQL日期时间类型的方法,但是您可能可以很容易地修改这段代码。

代码语言:javascript
复制
public class Mapper : DefaultMapper
{
    public override Func<object, object> GetFromDbConverter(Type DestType, Type SourceType)
    {
        if (DestType == typeof(DateTimeOffset) || DestType == typeof(DateTimeOffset?)
            || DestType == typeof(DateTime) || DestType == typeof(DateTime?))
        {
            return x =>
            {
                if (x is NpgsqlTimeStampTZ)
                {
                    if (DestType == typeof(DateTime))
                        return (DateTime)((NpgsqlTimeStampTZ)x);
                    if (DestType == typeof(DateTime?))
                        return (DateTime?)((NpgsqlTimeStampTZ)x);
                    if (DestType == typeof(DateTimeOffset))
                        return (DateTimeOffset)((NpgsqlTimeStampTZ)x);
                    if (DestType == typeof(DateTimeOffset?))
                        return (DateTimeOffset?)((NpgsqlTimeStampTZ)x);
                }
                if (x is NpgsqlTimeStamp)
                {
                    if (DestType == typeof(DateTime))
                        return (DateTime)((NpgsqlTimeStamp)x);
                    if (DestType == typeof(DateTime?))
                        return (DateTime?)((NpgsqlTimeStamp)x);
                }
                if (x is NpgsqlDate)
                {
                    if (DestType == typeof(DateTime))
                        return (DateTime)((NpgsqlDate)x);
                    if (DestType == typeof(DateTime?))
                        return (DateTime?)((NpgsqlDate)x);
                }

                return x;
            };
        }

        return base.GetFromDbConverter(DestType, SourceType);
    }

    public override Func<object, object> GetToDbConverter(Type DestType, Type SourceType)
    {
        if (SourceType == typeof(Instance)) {
            return x => { return ((Instance)x).ToDateTimeOffset(); } // etc or something like this
        }

        return base.GetToDbConverter(DestType, SourceType);
    }
}

如果您还有任何问题,请在github的“问题”页面上发布一个问题。干杯,亚当

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21075847

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档