Search code examples
c#uwprealm

How to store a System.Collections.Generic.Dictionary in realm-dotnet


I m trying to integrate Realm .NET in my uwp project and I would like to know if there is any way to store a System.Collections.Generic.Dictionary in realm-dotnet base. I tried this :

 public class Training : RealmObject
{
    public int Id { get; set; }
    public int Id_document { get; set; }
    public IDictionary<string, string>  Names { get; set;}
} 

But I m getting this error :

Error Fody/RealmWeaver: Training.Name is a 'System.Collections.Generic.IDictionary`2' which is not yet supported.

Thanks for advance,


Solution

  • Base request

    There isn't a way to directly store a System.Collections.Generic.Dictionary into Realm.
    On the Realm official website you can find all the informations that you're searching, as an example, here you can find the full list of the supported data types (Collections too).

    In order to save data with a structure as kind as a Dictionary, you would want to use a custom class that inherits from RealmObject with two IList<T> properties, such as:

    public class RealmDictionary : RealmObject {
        public IList<T> Keys { get; }
        public IList<T> Values { get; }
    }
    

    An in your class where you want to store the Dictionary, use an instance of the above RealmDictionary class:

    ...
    public RealmDictionary Names { get; set; }
    ...
    

    Update

    (Using NewtonsoftJson)
    If you must serialize the data into a Json string, you can setup your base class as:

    ...
    [JsonIgnore]
    public RealmDictionary RealmNames { get; set; }
    public Dictionary<string,string> Names {
        get {
            return RealmNames.AsDictionary
        }   
    }
    ...
    

    Then adding into the RealmDictionary class a property/method that constructs a dictionary with the values, something along the lines..

    public Dictionary<string,string> AsDictionary {
        get {
            Dictionary<string,string> temp = new Dictionary<>();
            for(int i = 0; i < Keys.Count; i++){
                temp.Add(Keys[i], Values[i]);
            }
            return temp;
        }
    }