MongoDB custom serializer implementation

后端 未结 1 1383
一生所求
一生所求 2021-01-04 21:33

I am new to MongoDB, and am trying to get the C# driver to work serializing F# classes. I have it working with the class automapper using mutable F# fields & a parameter

1条回答
  •  一整个雨季
    2021-01-04 22:17

    I figured this out in the end. I should have used bsonReader.GetCurrentBsonType() instead of bsonReader.CurrentBsonType. This reads the BsonType in from the buffer rather than just looking at the last thing there. I also fixed a subsequent bug derserializing. The updated method looks like this:

    public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) {
        if (nominalType != typeof(Calendar) || actualType != typeof(Calendar))
            throw new BsonSerializationException();
    
        if (bsonReader.GetCurrentBsonType() != BsonType.Document)
            throw new FileFormatException();
    
        bsonReader.ReadStartDocument();
        var id = bsonReader.ReadString("_id");
        bsonReader.ReadName();
        var ser = new ArraySerializer();
        var holidays = (DateTime[])ser.Deserialize(bsonReader, typeof(DateTime[]), null);
        bsonReader.ReadEndDocument();
        return new Calendar(id, holidays);
    }
    

    0 讨论(0)
提交回复
热议问题