Story Details for articles
2 - DocumentDB - Golf Tracker Article - Techniques
Data Management Made Easy
In order to store JSON documents of different shapes into the same collection, there has to be a way to query for a collection of documents by a particular type. The easiest way to do this is simply that, including an attribute to the JSON document called "type" and labeling it based on the type of document that it is.
The JSON document might look like this:
In this case I have two types of documents, a Golfer, and Golf Clubs. So I can then simply add the "type" attribute to the JSON document and label it either "golfer" or "golfclub". But really, that would be a pain to have to remember to include that "type" attribute every time I'm creating a new document and I won't be working with JSON documents in my WebApi project, I'll be working with .Net classes. There's an easy solution for that.
I've created an EntityBase class that holds the Id field for each document, plus the "type" property that will be loaded with the value for the derived class. Let me show you what I mean.
The Golfer Class
The golfer class contains any number of properties, but I don't want to worry about whether or not it has the "type" property, so I just inherit from the EntityBase class, and set a value in the base constructor, and I'm done!
Here's a look at the golfer C# class:
You'll see that it inherits from the EntityBase class and simply passes in the name of the class itself in lowercase to the base constructor, and that's all that's necessary.
When it comes time to adding additional properties to this class, I can just do it and I'll be done. The class is still going to be part of the "golfer" type and it will be returned as a collection based on that type.
Here's a look at the EntityBase class:
When the "golfer" type value is passed into the EntityBase constructor, it gets returned as the value for the "type" property. And when the .Net Golfer class is serialized by the JSON serializer to be stored in DocumentDB, the "type" property just goes along with it and it serialized along with all the other properties and values.
It's important to know that you only need to inherit the EntityBase class on the "root" class. Any of the embedded classes should not inherit from the EntityBase class.
This isn't all that's needed to make this work, but it's the basis. In the Visual Studio Deep Dive article, I'll go over how it's implemented in the RepositoryBase class.
Continue on to see a demonstration of how the client operations work.