投影中未包含字段时,不会调用自定义通用Mongo C#序列化程序

时间:2019-02-21 00:12:25

标签: c# mongodb bson

当Mongo的投影中不包含该属性时,不会调用我的通用序列化器。 这是我的正在序列化/反序列化的类:

   public class User : ServiceMongoIdentity
    {
   /// properties ommitted for brevity
        [BsonIgnoreIfDefault]        
        [BsonSerializer(typeof (StringTypeBsonSerializer<LanguageCode>))]
        [BsonDefaultValue(LanguageCode.EnUs)]
        public LanguageCode Language { get; set; } = LanguageCode.EnUs;
}
 var users = await userDataClient.UserCrud.GetAll(terryberryDataContext,nameof(User.Language));

供参考的GetAll定义如下

    Task<List<T>> GetAll(DataContext dataContext, params string[] includedfields);

这是我的序列化器

 public class StringTypeBsonSerializer<T> : SerializerBase<T> where T:StringTypeBase<T>, new()
    {
        /// <summary>Deserializes a value.</summary>
        /// <param name="context">The deserialization context.</param>
        /// <param name="args">The deserialization args.</param>
        /// <returns>A deserialized value.</returns>
        public override T Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {

            if (context.Reader.CurrentBsonType != BsonType.String)
            {
                Console.WriteLine("returning");
                return null;
            }


            T stringType = new T();

           return stringType.FromString(context.Reader.ReadString());

        }


        public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, T value)
        {

            context.Writer.WriteString(value.ToString());
        }


    }

此代码会导致错误,因为我不再使用自定义序列化器投影字段

 var users = await userDataClient.UserCrud.GetAll(terryberryDataContext);
System.InvalidCastException: Unable to cast object of type 'System.String' to type 'Terryberry.Users.Shared.Domain.Constants.LanguageCode'.
   at lambda_method(Closure , Object , Object )
   at MongoDB.Bson.Serialization.BsonMemberMap.ApplyDefaultValue(Object obj)
   at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.DeserializeClass(BsonDeserializationContext context)

两种变通办法是要求具有BsonRequired的字段或删除[BsonDefaultValue(LanguageCode.EnUs)]

0 个答案:

没有答案