我有一个uint32来序列化到MongoDB。
我以前可以使用https://jira.mongodb.org/browse/CSHARP-252
中的以下代码执行此操作public class AlwaysAllowUInt32OverflowConvention : ISerializationOptionsConvention
{
public IBsonSerializationOptions GetSerializationOptions(MemberInfo memberInfo)
{
Type type = null;
var fieldInfo = memberInfo as FieldInfo;
if (fieldInfo != null)
{
type = fieldInfo.FieldType;
}
var propertyInfo = memberInfo as PropertyInfo;
if (propertyInfo != null)
{
type = propertyInfo.PropertyType;
}
if (type == typeof(uint))
{
return new RepresentationSerializationOptions(BsonType.Int32) { AllowOverflow = true };
}
else
{
return null;
}
}
}
但是在新的MongoDB库中,ISerializationOptionsConvention
和RepresentationSerializationOptions
不存在。我已经看过了,看不到如何注册默认的ConventionPack(?)以允许uint32在新库上溢出int32。
如何在不向我的POCO添加BsonRepresentation属性的情况下执行此操作?
答案 0 :(得分:6)
我可以想到两种方法可以做到这一点。可能最简单的方法是简单地为类型UInt32注册一个适当配置的序列化器,如下所示:
var uint32Serializer = new UInt32Serializer(BsonType.Int32, new RepresentationConverter(true, true));
BsonSerializer.RegisterSerializer(uint32Serializer);
如果你想使用约定(在自动映射类时仅应用),你可以这样做:
public class AlwaysAllowUInt32OverflowConvention : IMemberMapConvention
{
public string Name
{
get { return "AlwaysAllowUInt32Overflow"; }
}
public void Apply(BsonMemberMap memberMap)
{
if (memberMap.MemberType == typeof(UInt32))
{
var uint32Serializer = new UInt32Serializer(BsonType.Int32, new RepresentationConverter(true, true));
memberMap.SetSerializer(uint32Serializer);
}
}
}
并按照以下方式注册会议:
var alwaysAllowUInt32OverflowConvention = new AlwaysAllowUInt32OverflowConvention();
var conventionPack = new ConventionPack();
conventionPack.Add(alwaysAllowUInt32OverflowConvention);
ConventionRegistry.Register("AlwaysAllowUInt32Overflow", conventionPack, t => true);
答案 1 :(得分:1)
您可以通过IBsonSerializer
来完成public class UInt32ToInt64Serializer : IBsonSerializer
{
public object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
return (uint)context.Reader.ReadInt64();
}
public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
{
context.Writer.WriteInt64((uint)value);
}
public Type ValueType { get { return typeof (uint); } }
}
和序列化程序应该注册
BsonSerializer.RegisterSerializer(typeof(uint), new UInt32ToInt64Serializer());