mongodb - 替换 MongoDB 驱动程序 v2.4.0 中的 BsonBaseSerializer

标签 mongodb

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

最佳答案

确实没有足够的问题来给出完整的答案,但您正在寻找的更改记录在 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));
    }
}

差别不大,但与大多数驱动程序更改一样,它们虽然很小,但会造成破坏。

关于mongodb - 替换 MongoDB 驱动程序 v2.4.0 中的 BsonBaseSerializer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41055414/

相关文章:

JSON哲学

javascript - Mongodb 返回填充对象但保存清空一些字段

MongoDB - 将简单字段更改为对象

java - MongoDB/Morphia 中的引用

javascript - 从 Mongoose 的多个集合中获取数据?

javascript - Mongoose 在插入文档时调用字段的函数

mongodb - 如何使用Pig在mongodb中按_id进行过滤

javascript - 通过数组在 mongodb 中查找某个字段的文档?

javascript - 如何在 join sails js 中添加另一个字段

node.js - 更新插入不适用于 updateOnebulkWrite v3.4