This works in principle, but these are Entity Framework models - navigation properties and all. I quickly ran into object cycles when trying to serialize these models, and needed a way to ignore their navigation properties.
The problem was that navigation properties were causing object cycles. Very well, let’s set them to
null and they won’t be serialized. Furthermore, using JSON.NET’s
NullValueHandling option can have the nullified properties be ignore entirely during serialization!
This works, but it can be better. Firstly, the length of our selector grows as the number of unwanted properties grows. In the same vein, we’re still serializing every other property of each data point. Ideally, we want to only serialize the properties that are relevant to our visualizations, which both avoids object cycles and slims down the size of our page.
By selecting a new object for each data point, we can pick and choose exactly which properties we want to include in our serialized data:
Select() method with anonymous types has proven to be an incredibly flexible tool for transforming collections of data. In this case, it helped cut down on webpage size, but there are countless other ways in which it can be useful.
One piece of general knowledge I’ve gained from this process is to only transmit the data that needs to be transmitted. I initially started using
Select() with anonymous types to avoid object cycles, but I’ve since converted every serializtion of this kind to use it. It cuts down on page size and clarifies which properties are relevant to the data visualization.