RavenDB Survival Tip #3: Handling Polymorphism

Categories: RavenDB

If you want to store objects in your database that are implementations of interfaces or base classes, you can do this pretty easily by alternating Raven’s JSON serializer settings so that when Raven serializes your object, it includes a special “$type” property in the JSON that records the full type name of the object.

The documentation for RavenDB actually mentions this, but there’s a little change that I do to make it a little more efficient.  The docs say to use a TypeNameHandling convention of “All” but this will emit the $type property on every single object.  This is a waste of space and creates a lot of clutter.  You should instead use TypeNameHandling.Auto.  This setting will only include the $type property if the type of the property does not match the actual type of the object. 

Here’s how you’d set this up (I’m assuming that you have a DocumentStore instance available).  You’d perform this setup only when initially creating the DocumentStore (once per app):

store.Conventions.CustomizeJsonSerializer = serializer =>
    serializer.TypeNameHandling = 

No Comments