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

前端 未结 4 627
逝去的感伤
逝去的感伤 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:36

    ConventionProfile was deprecated. If you don't want to apply the rule globally, but only for a specific class (this should go somewhere in your app startup):

    var pack = new ConventionPack { new GuidAsStringRepresentationConvention () };
    ConventionRegistry.Register("GuidAsString", pack, t => t == typeof (MyClass));
    
    public class GuidAsStringRepresentationConvention : ConventionBase, IMemberMapConvention
        {
            public void Apply(BsonMemberMap memberMap)
            {
                if (memberMap.MemberType == typeof(Guid))
                {
                    var serializer = memberMap.GetSerializer();
                    var representationConfigurableSerializer = serializer as IRepresentationConfigurable;
                    if (representationConfigurableSerializer != null)
                    {
                        var reconfiguredSerializer = representationConfigurableSerializer.WithRepresentation(BsonType.String);
                        memberMap.SetSerializer(reconfiguredSerializer);
                    }
                }
            }
        }
    

提交回复
热议问题