Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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:</p> <pre><code>MyRootClass obj = new MyDerivedClass(); collection.Insert(obj); </code></pre> <p>The Insert statement could also have been written:</p> <pre><code>collection.Insert&lt;MyRootClass&gt;(obj); </code></pre> <p>but it's easier to let the compiler infer the type parameter.</p> <p>Since the actual type of obj is different than the nominal type the "_t" discriminator will be written.</p> <p>When reading back the object you will have to ensure that MyDerivedClass has been properly registered:</p> <pre><code>BsonClassMap.RegisterClassMap&lt;MyDerivedClass&gt;(); </code></pre> <p>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).</p> <p>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:</p> <pre><code>Type myDerivedClass; // your plugged-in class var registerClassMapDefinition = typeof(BsonClassMap).GetMethod("RegisterClassMap", new Type[0]); var registerClassMapInfo = registerClassMapDefinition.MakeGenericMethod(myDerivedClass); registerClassMapInfo.Invoke(null, new object[0]); </code></pre> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload