RedRose
RedRose

Reputation: 689

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 ?

Upvotes: 1

Views: 1172

Answers (2)

Dĵ ΝιΓΞΗΛψΚ
Dĵ ΝιΓΞΗΛψΚ

Reputation: 5679

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

Upvotes: 3

dododo
dododo

Reputation: 4847

Check this:

  1. SetElementName way:

    BsonClassMap.RegisterClassMap<Address>(cm =>
    {
        cm.MapField(e => e.CountryCode).SetElementName("COUNTRY_CODE");
    });
    var address = new Address();
    var bson = address.ToBsonDocument();  
    // bson: { "COUNTRY_CODE" : null }
    
  2. BsonElement attribute way:

    public class Address
    {
        [BsonElement("COUNTRY_CODE")]
        public string CountryCode { get; set; }
    } 
    

Upvotes: 1

Related Questions