I’m using RavenDB & need to store dynamic data like:
public class User {
public string Name;
public dynamic Data;
}
It appears that I could use many different types such as dynamic, RavenJObject, DynamicJsonObject, ExpandoObject, Dictionary<string, object>, but I don’t know what the differences are.
Could someone explain the options for dynamic data? I care less about querying & more about easy storage & retrieval.
Problem
Here’s the deal, if you have a
dynamicproperty then RavenDB will always deserialize it as aRavenJObject. For example:This looks harmless & works fine when you create your user. But when you Load user, RavenDB doesn’t know what type you want for
dynamicso it usesRavenJObject. You can’t dynamically create properties (expando style) withRavenJObjectso this fails:My Solution
Use an
ExpandoObjectand explicitly define its type in the property that is serialized. That lets RavenDB (or JSON i guess) know what type you’re expecting & it doesn’t have to guessRavenJObject. Then, to keep your syntactical magic, wrap the property with a dynamic accessor.There are ways to make the expando object private & to create a setter for
Data, but you get the idea.More Problems
Update: Unfortunately this solution exposes more problems. Say you store a list of strings in your dynamic data:
After you serialize/deserialize, JSON/Raven again doesn’t know what type you are expecting. So if you try this (see below) then it compiles but you get a runtime exception Cannot implicitly convert type ‘Raven.Abstractions.Linq.DynamicList’ to ‘System.Collections.Generic.List’: