Search code examples
c#mongodbmongodb-.net-driver

Setting MongoDb to change a property to UpperCase


I have the following poco (other properties omitted for simplicity) :

public class Address
{
   . . .    
  public string CountryCode { get; set; }
   . . .
} 

What do I have to do in the BsonClassMap to enforce Upper Case only for this property. For Example "us" will be stored in the db as "US"

BsonClassMap.RegisterClassMap<Address>(cm =>
            {
               // what am I missing here ?
            });

Or am I approaching this the wrong way ?


Solution

  • here's a custom serializer attribute you can decorate the country code property with:

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class UpperCaseAttribute : BsonSerializerAttribute
    {
        public UpperCaseAttribute() : base(typeof(UpperCaseSerializer)) { }
    
        private class UpperCaseSerializer : SerializerBase<string>
        {
            public override void Serialize(BsonSerializationContext ctx, BsonSerializationArgs args, string value)
            {
                if (value is null)
                    ctx.Writer.WriteNull();
                else
                    ctx.Writer.WriteString(value.ToUpper());
            }
    
            public override string Deserialize(BsonDeserializationContext ctx, BsonDeserializationArgs args)
            {
                switch (ctx.Reader.CurrentBsonType)
                {
                    case BsonType.String:
                        return ctx.Reader.ReadString();
    
                    case BsonType.Null:
                        ctx.Reader.ReadNull();
                        return null;
    
                    default:
                        throw new BsonSerializationException($"'{ctx.Reader.CurrentBsonType}' values are not valid on properties decorated with an [UpperCase] attribute!");
                }
            }
        }
    

    usage:

    public class Address
    {
      [UpperCase]  
      public string CountryCode { get; set; }
    }