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

前端 未结 4 647
逝去的感伤
逝去的感伤 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条回答
  •  Happy的楠姐
    2021-01-13 09:30

    An alternative to performing this globally without setting a Convention (which I believe is overkill given the actual question was effectively: "how can this be applied globally") can be done by simply calling one line of code:

    BsonSerializer.RegisterSerializer(typeof(Guid), 
        new GuidSerializer(BsonType.String));
    

    Just make sure this is the first thing that fires in terms of MongoDb's serialization configuration (even before class maps are registered, the same is true for the convention based solutions posted).

    Personally I see this as a better solution than creating a convention with an 'always return true' predicate, that most seem to be suggesting. Conventions are great for more complex scenarios, and for grouping sets of serialization configurations, where the predicate is actually used, and multiple Conventions are bundled into a ConventionPack. But for simply applying a global serialization format, just keep it simple with the above line of code.

    If you later decide you have a legitimate Convention that requires a variation of this rule, just register it in order to overwrite the global rule we have set, just as your Convention would overwrite the default global rule, which is set to have Guid's represented as BsonType.Binary. The net result then would be the global rule taking precedence, followed by the Convention, which will overwrite our custom global rule only in such cases where the custom ConventionPack is applicable (based on your custom predicate).

提交回复
热议问题