I’m using the official MongoDb C# driver.
My scenario: I store objects into MongoDb. All objects are instances of classes that inherit from the same root class.
At design time I do not know all classes that can be stored (i.e they can be plugged in) – so I need some way to tell the serializer/driver how to map the classes to documents (descriminators in the document).
Anyone got any ideas?
The official C# driver will write a “_t” discriminator value whenever the actual type of an object is different than the nominal type. So for example:
The Insert statement could also have been written:
but it’s easier to let the compiler infer the type parameter.
Since the actual type of obj is different than the nominal type the “_t” discriminator will be written.
When reading back the object you will have to ensure that MyDerivedClass has been properly registered:
or the serializer won’t recognize the discriminator (this may seem like a restriction, but it’s only logical that the serializer can only work with types it knows about).
You mentioned that you don’t know the classes at compile time, so the above registration code must be invoked dynamically. One way to do it is:
Technically, the serialization is not using reflection; it is metadata driven. Reflection is used once to construct the class map, but after that the class map is used directly without reflection, and the overhead is rather low.