Search code examples
c#mongodbmongodb-.net-driver

Adding a Dictionary<DateTime,T> to a mongoDb when using C# monogDb drivers


Currently I am trying to add an object that has a property Dictionary<DateTime,T> to a mongoDb by using the c# monogDb driver.

In the project I have a lot of related legacy code so I can't easily change the dictionary to any other type. Dictionaries are a quiter common data type in my project so adding a seperate tag above all properties to define the serializer isn't really a good options. I would like to find a general way serializing the dictionary.

I have read the following related post, and tried applying the convetion, however this seems to give me issues with the child serializer.

When adding an item I get the following error:

System.InvalidOperationException: ValueFactory attempted to acces the value property of this instace.

I can't figure out what the issue exactly is or how to solve it.


Solution

  • As recommended by @Poul Bak the issue can be solved as the following:

    As an example I will use a class Item

    public class Item {
         public Dictionary<DateTime, AnotherItem> Dictionary {get;set;}
    }
    

    Create a value converter

        public class DateTimeDictionaryConverter<T>: ValueConverter<Dictionary<DateTime, T>, string> {
    
        public DateTimeDictionaryConverter() : base(
            v => ConvertToJson(v),
            v => ConvertFromJson(v))
        {
        }
    
        private static string ConvertToJson(Dictionary<DateTime, T> dict)
        {
            return JsonSerializer.Serialize(dict);
        }
    
        private static Dictionary<DateTime, T> ConvertFromJson(string value)
        {
            return JsonSerializer.Deserialize<Dictionary<DateTime, T>>(value);
        }
    }
    

    Then add the converter to the correct entity in the db context

    modelBuilder.Entity<Item>().Property(i => i.Dictionary).HasConversion(new DateTimeDictionaryConverter<OtherItem>())
    

    This wil work, the only remaining downside is having to add the value converter for each item with a dictionary