How can I tell the MongoDB C# driver to store all Guids in string format?

前端 未结 4 624
逝去的感伤
逝去的感伤 2021-01-13 08:47

I\'m currently applying the [BsonRepresentation(BsonType.String)] attribute to all Guid properties in my domain models to have those properties ser

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-13 09:17

    While using conventions will work, pay attention to two important (and related) points:

    1. The filter parameter is required, and if the filter is too general (for example: t => true), it can overwrite other registered conventions.
    2. Be aware that the order of registered conventions is important, first register specific filters and after register general conventions.

    Another option is to create a BSON Class Map for type Guid, which sets the representation to string:

    if (!BsonClassMap.IsClassMapRegistered(typeof(Guid))) {
        BsonClassMap.RegisterClassMap(cm => {
            cm.AutoMap();
            cm.Conventions.SetSerializationOptionsConvention(new  TypeRepresentationSerializationOptionsConvention(typeof(Guid), BsonType.String));
        });
    }
    

    This should be done before any reading/writing using BsonSerializer, otherwise the default Class Map will be created, and you wont be able to change the Class Map.

提交回复
热议问题