在MongoDB驱动程序v2.4.0中替换BsonBaseSerializer

时间:2016-12-09 07:43:17

标签: mongodb

我们已将MongoDB驱动程序从v1.9.3迁移到v2.4.0。我们使用了BsonBaseSerializer,这在v2.4.0中不存在。什么是v2.4.0中BsonBaseSerializer的替代?

1 个答案:

答案 0 :(得分:3)

没有足够的问题可以给出完整的答案,但是您正在寻找的更改记录在mongo文档中的序列化中。

http://mongodb.github.io/mongo-csharp-driver/2.4/reference/bson/serialization/#implementation-1

最大的变化是他们现在在基类上采用了一种类型。

所以

V1驱动程序代码

public class IntegerCoercion : BsonBaseSerializer
{
    public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
    {
        if (bsonReader.CurrentBsonType == BsonType.Int32)
        {
            return bsonReader.ReadInt32();
        }
        if (bsonReader.CurrentBsonType == BsonType.String)
        {
            var value = bsonReader.ReadString();
            if (string.IsNullOrWhiteSpace(value))
            {
                return null;
            }
            return Convert.ToInt32(value);
        }
        bsonReader.SkipValue();
        return null;
    }

    public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
    {
        if (value == null)
        {
            bsonWriter.WriteNull();
            return;
        }
        bsonWriter.WriteInt32(Convert.ToInt32(value));
    }
}

V2驱动程序代码

public class IntegerCoercion : SerializerBase<object>
{
    public override object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        if (context.Reader.CurrentBsonType == BsonType.Int32)
        {
            return context.Reader.ReadInt32();
        }
        if (context.Reader.CurrentBsonType == BsonType.String)
        {
            var value = context.Reader.ReadString();
            if (string.IsNullOrWhiteSpace(value))
            {
                return null;
            }
            return Convert.ToInt32(value);
        }
        context.Reader.SkipValue();
        return null;
    }

    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
    {
        if (value == null)
        {
            context.Writer.WriteNull();
            return;
        }
        context.Writer.WriteInt32(Convert.ToInt32(value));
    }
}

并没有太大的区别,但与大多数驾驶员的变化一样,它们只是微不足道而是破碎。