Search code examples
c#mongodbmongodb-.net-driver

Map different cases out of mongo database


I have a mongo dataset containing objects where the property name cases differ. e.g.

{
"prop1": "value1",
"prop2": "value2"
},
{
"Prop1": "value3",
"proP2": "value4"
},
{
"PROP1": "value5",
"ProP2": "value6"
}

Is there a way I can map this into my class.

public class MyClass
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

I can see you can use the BsonDiscriminator attribute to specify a particular casing but can I handle multiple casings somehow?


Solution

  • you can achieve it with the use of ISupportInitialize and BsonExtraElements like so:

    public class MyClass : ISupportInitialize
    {
        public string Prop1 { get; set; }
        public string Prop2 { get; set; }
    
        [BsonExtraElements]
        public IDictionary<string, object> Extras { get; set; }
            = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
    
        public void BeginInit() { } //nothing to do here
    
        public void EndInit()
        {
            foreach (var prop in typeof(MyClass).GetProperties())
            {
                if (Extras.Remove(prop.Name, out var value))
                {
                    prop.SetValue(this, value);
                }
            }
        }
    }
    

    ideally, you should just run a database migration to rename all the field names to be the same. otherwise you won't be able to query data properly. i.e. properties with casing that doesn't match what your poco has won't get matched.