是否从MongoDB的最新C#驱动程序中删除了IBsonSerializationOptions?

时间:2015-07-02 07:38:53

标签: c# mongodb mongodb-.net-driver

我的C#项目中有以下源代码,可以使用mongocsharpdriver 1.8.3版成功构建。但是在我将MongoDB C#驱动程序升级到2.0.1之后,编译失败并显示错误,指示找不到IBsonSerializationOptionsDateTimeSerializationOptions类(接口),并且还检查了所有命名空间程序集,似乎从最新版本的MongoDB C#驱动程序中删除了这些类型。

public void Apply(BsonMemberMap memberMap)
{
    IBsonSerializationOptions options = null;
    switch (memberMap.MemberInfo.MemberType)
    {
       case MemberTypes.Property:
           PropertyInfo propertyInfo = (PropertyInfo)memberMap.MemberInfo;
           if (propertyInfo.PropertyType == typeof(DateTime) ||
               propertyInfo.PropertyType == typeof(DateTime?))
               options = new DateTimeSerializationOptions(DateTimeKind.Local);
           break;
       case MemberTypes.Field:
           FieldInfo fieldInfo = (FieldInfo)memberMap.MemberInfo;
           if (fieldInfo.FieldType == typeof(DateTime) ||
               fieldInfo.FieldType == typeof(DateTime?))
               options = new DateTimeSerializationOptions(DateTimeKind.Local);
           break;
       default:
           break;
   }
   memberMap.SetSerializationOptions(options);
}

我的问题是,在最新版本的MongoDB C#驱动程序中,这些类型的等价物是什么?

2 个答案:

答案 0 :(得分:2)

在C#Driver 2.0中,您需要实现IBsonSerializer

public class LocalTimeSerializer : IBsonSerializer
{
    public object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        return context.Reader.ReadDateTime();
    }

    public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
    {
        context.Writer.WriteDateTime(((DateTime)value).ToLocalTime().Ticks);
    }

    public Type ValueType { get { return typeof(DateTime); } }
}

你应该注册序列化器

BsonSerializer.RegisterSerializer(typeof(DateTime), new LocalTimeSerializer());

答案 1 :(得分:1)

在2.0版本的C#驱动程序中,序列化选项已被删除,并且已成为序列化程序本身的属性。您可以配置适当配置的序列化程序并使用它来代替设置序列化选项。

2.0版本驱动程序的约定实现如下:

public class LocalDateTimeConvention : IMemberMapConvention
{
    public string Name
    {
        get { return "LocalDateTime"; }
    }

    public void Apply(BsonMemberMap memberMap)
    {
        if (memberMap.MemberType == typeof(DateTime))
        {
            var dateTimeSerializer = new DateTimeSerializer(DateTimeKind.Local);
            memberMap.SetSerializer(dateTimeSerializer);
        }
        else if (memberMap.MemberType == typeof(DateTime?))
        {
            var dateTimeSerializer = new DateTimeSerializer(DateTimeKind.Local);
            var nullableDateTimeSerializer = new NullableSerializer<DateTime>(dateTimeSerializer);
            memberMap.SetSerializer(nullableDateTimeSerializer);
        }
    }
}