I always try to keep my models seperate from the implementation or configuration. EF Core 2.1 added great support for custom type converters with HasConversion
. MongoDB also has a support for custom type conversion, though it is not quite as well documented.
The basic premise revolves around implementing IBsonSerializer<TType>
. Let's suppose I have a Bitrate
struct I want to convert to a long
. Bitrate
has a BitsPerSecond
property which is the underlying long
value. My BitrateSerializer
will look something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class BitrateSerializer : IBsonSerializer<Bitrate> { public Type ValueType => typeof(Bitrate); public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Bitrate value) { BsonSerializer.Serialize(context.Writer, value.BitsPerSecond); } Bitrate IBsonSerializer<Bitrate>.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { return new Bitrate(BsonSerializer.Deserialize<long>(context.Reader)); } public object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { // You can reuse Deserialize method, but ensure you don't end up in an infinte loop. return new Bitrate(BsonSerializer.Deserialize<long>(context.Reader)); } public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value) { Serialize(context, args, (Bitrate)value); } } |
This being Mongo driver, it is not so easy to add unit tests. I'll cover this another time.