4

我正在使用最新版本的NodaTimeMongo DB Official Driver。我有一个简单的 POCO 类,它在一些属性中使用 NodaTimeZonedDateTime作为 .NET DateTime 的替代品。

public class MyPOCO
{
    [BsonId]
    [Key]
    public ObjectId SomeId { get; set; }

    public string SomeProperty { get; set; }

    public ZonedDateTime SomeDateTime { get; set; }
}

我可以轻松地将模型放入集合中,但是当我尝试读取查询的模型时,我得到以下信息MongoDB.Bson.BsonSerializationException

值类 NodaTime.ZonedDateTime 无法反序列化

解决/解决此问题的好方法或最佳实践是什么?

更新

在发布我的问题解决方案后,我面临一个可能的新问题......当我查询集合并在查询中使用 DateTime 时,就像where SomeDateTime < now' (where现在is a variable I create from system time) it seems that each document must be deserialized using my可以评估 where 子句之前的 ZonedDateTimeSerializer`。这看起来像一个很大的性能问题,不是吗?我真的不得不考虑再次回到 BCL DateTime,即使它很痛。

更新 2

我接受了我的解决方案ZonedDateTimeSerializer,但我对 NodaTime 与 MongoDB 的结合感到不舒服,虽然两者都是很好的单独解决方案。但是如果没有大量的操作,它们目前不能很好地协同工作。

4

2 回答 2

5

没关系,经过大量阅读和实验,终于找到了。我编写了一个自定义BsonBaseSerializer实现来处理ZonedDateTime.

这是我的代码ZonedDateTimeSerializer

/// <summary>
/// Serializer for the Noda
/// </summary>
public class ZonedDateTimeSerializer : BsonBaseSerializer
{
    private static ZonedDateTimeSerializer __instance = new ZonedDateTimeSerializer();

    /// <summary>
    /// Initializes a new instance of the ZonedDateTimeSerializer class.
    /// </summary>
    public ZonedDateTimeSerializer()
    {
    }

    /// <summary>
    /// Gets an instance of the ZonedDateTimeSerializer class.
    /// </summary>
    public static ZonedDateTimeSerializer Instance
    {
        get { return __instance; }
    }

    /// <summary>
    /// Deserializes an object from a BsonReader.
    /// </summary>
    /// <param name="bsonReader">The BsonReader.</param>
    /// <param name="nominalType">The nominal type of the object.</param>
    /// <param name="actualType">The actual type of the object.</param>
    /// <param name="options">The serialization options.</param>
    /// <returns>
    /// An object.
    /// </returns>
    public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
    {
        VerifyTypes(nominalType, actualType, typeof(ZonedDateTime));

        var bsonType = bsonReader.GetCurrentBsonType();
        if (bsonType == BsonType.DateTime)
        {
            var millisecondsSinceEpoch = bsonReader.ReadDateTime();
            return new Instant(millisecondsSinceEpoch).InUtc();
        }

        throw new InvalidOperationException(string.Format("Cannot deserialize ZonedDateTime from BsonType {0}.", bsonType));
    }

    /// <summary>
    /// Serializes an object to a BsonWriter.
    /// </summary>
    /// <param name="bsonWriter">The BsonWriter.</param>
    /// <param name="nominalType">The nominal type.</param>
    /// <param name="value">The object.</param>
    /// <param name="options">The serialization options.</param>
    public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
    {
        if (value == null)
            throw new ArgumentNullException("value");

        var ZonedDateTime = (ZonedDateTime)value;
        bsonWriter.WriteDateTime(ZonedDateTime.ToInstant().Ticks);
    }
}

不要忘记注册序列化程序。我无法找到如何为每种类型注册 Serializer,但您可以为每种类型注册它,如下所示:

BsonClassMap.RegisterClassMap<MyPOCO>(cm =>
{
    cm.AutoMap();
    cm.GetMemberMap(a => a.SomeDateTime).SetSerializer(ZonedDateTimeSerializer.Instance);
});

希望这可以帮助。

于 2013-07-26T16:14:38.520 回答
1

这是 thmshd 类的修改版本,它也存储时区信息:

public class ZonedDateTimeSerializer : IBsonSerializer<ZonedDateTime>
{
    public static ZonedDateTimeSerializer Instance { get; } = new ZonedDateTimeSerializer();

    object IBsonSerializer.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        return Deserialize(context, args);
    }

    public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, ZonedDateTime value)
    {
        if (value == null)
            throw new ArgumentNullException(nameof(value));

        var zonedDateTime = value;

        SerializeAsDocument(context, zonedDateTime);
    }

    private static void SerializeAsDocument(BsonSerializationContext context, ZonedDateTime zonedDateTime)
    {
        context.Writer.WriteStartDocument();
        context.Writer.WriteString("tz", zonedDateTime.Zone.Id);
        context.Writer.WriteInt64("ticks", zonedDateTime.ToInstant().Ticks);
        context.Writer.WriteEndDocument();
    }

    public ZonedDateTime Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        var bsonType = context.Reader.GetCurrentBsonType();

        if (bsonType != BsonType.Document)
        {
            throw new InvalidOperationException($"Cannot deserialize ZonedDateTime from BsonType {bsonType}.");
        }

        context.Reader.ReadStartDocument();
        var timezoneId = context.Reader.ReadString("tz");
        var ticks = context.Reader.ReadInt64("ticks");
        var timezone = DateTimeZoneProviders.Tzdb.GetZoneOrNull(timezoneId);

        if (timezone == null)
        {
            throw new Exception($"Unknown timezone id: {timezoneId}");
        }

        context.Reader.ReadEndDocument();

        return new Instant(ticks).InZone(timezone);
    }

    public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
    {
        if (value == null)
        {
            throw new ArgumentNullException(nameof(value));
        }

        var zonedDateTime = (ZonedDateTime)value;

        SerializeAsDocument(context, zonedDateTime);
    }

    public Type ValueType => typeof(ZonedDateTime);
}

它可以像这样全局注册:

BsonSerializer.RegisterSerializer(ZonedDateTimeSerializer.Instance);

编辑:与其序列化到子文档,不如利用 NodaTimes 内置的字符串解析。

连载:

context.Writer.WriteString(ZonedDateTimePattern.CreateWithInvariantCulture("G", DateTimeZoneProviders.Tzdb).Format(zonedDateTime));

反序列化:

        var zonedDateTimeString = context.Reader.ReadString();
        var parseResult = ZonedDateTimePattern.CreateWithInvariantCulture("G", DateTimeZoneProviders.Tzdb)n.Parse(zonedDateTimeString);

        if (!parseResult.Success)
        {
            throw parseResult.Exception;
        }

        return parseResult.Value;
于 2017-07-07T00:36:00.903 回答