I have a model with a property (let's say it's called X) of type DateTime?.
I want to set like [BsonDateTimeOptions(DateOnly = true)] but using the class mapper in mongo c# driver like:
BsonClassMap.RegisterClassMap<MyModel>(cm =>
{
cm.AutoMap();
cm.MapMember(c => c.X).SetSerializer(new DateTimeSerializer(dateOnly: true));
});
But for some reason, I'm getting an error because the property is Nullable, for normal DateTime type it works properly.
Why I need this because I need to save the value of X as date only without timezone.
I already tried to build custom serializer but I'm getting an error when deserializing saying:
ReadBsonType can only be called when State is Type, not when State is Value
And here's the custom serializer:
public class DateTimeNullableSerialzier : DateTimeSerializer, IBsonSerializer
{
public object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
if (context.Reader.CurrentBsonType == BsonType.Null)
return null;
return base.Deserialize(context, args);
}
public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
{
if (value is null)
context.Writer.WriteNull();
else
base.Serialize(context, args, (DateTime)value);
}
}