我们已将 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/