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

Has IBsonSerializationOptions been removed from the latest C# driver of MongoDB?

我的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# 驱动程序中,这些类型的等效项是什么?

在 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());

在 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);
        }
    }
}