Hi all,
I’m using the C# driver and needed to write a custom serializer for a collection that contains different document types (all children of the same base type)
In the deserialize method I figure out the document type and deserialize to the relevant class
In the serialize method I wanted to use the driver’s default behavior since I didn’t need to do anything special, so I created an instance of a BsonClassMapSerializer and used its serialize method
The problem is that when I do this it doesn’t generate a value for the _id property
So the question is do I need to do it myself because I’m using a custom serializer, or am I just doing something wrong here with how I’m serializing?
I thought that using the ClassMapSerializer will take care of this for me
Some code example for better understanding:
public class BaseClass
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Title { get; set; }
}
public class Child1 : BaseClass
{
public string Description { get; set; }
public int Value { get; set; }
}
public class Child2 : BaseClass
{
public string Creator { get; set; }
public int Amount { get; set; }
public int NumberOfUsers { get; set; }
}
public class MyCustomSerializer : IBsonSerializer<BaseClass>, IBsonDocumentSerializer
{
public Type ValueType => typeof(BaseClass);
private readonly IBsonDocumentSerializer _baseSerializer = new BsonClassMapSerializer<BaseClass>(BsonClassMap.LookupClassMap(typeof(BaseClass)));
public BaseClass Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
// Deserialize to the relevant child class
}
public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, BaseClass value)
{
// This doesn't give a value to _id field so the document is inserted with _id: null
_baseSerializer.Serialize(context, args, value);
}
public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
{
Serialize(context, args, (BaseInteractionInstance)value);
}
public bool TryGetMemberSerializationInfo(string memberName, out BsonSerializationInfo serializationInfo)
{
return _baseSerializer.TryGetMemberSerializationInfo(memberName, out serializationInfo);
}
object IBsonSerializer.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
return Deserialize(context, args);
}
}