Search code examples
c#mongodbserializationmongodb-.net-driver

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


To serialize the Guid to string I have no problem since I am using this code : https://stackoverflow.com/a/33258168/4148788

    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);
                }
            }
        }
    }

If I try to do the same for the Guid? it doesn't work

            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);
                }
            }

This line is always null:

                var representationConfigurableSerializer = serializer as IRepresentationConfigurable;

How do you do for nullable Guids?


Solution

  • Do you need to reconfigure the current serializer or can you just replace it? replacing it would be simpler.

    The nullable type BSON serializers are wrapped in a decorator serializer type (NullableSerializer<>), We can just check for the MemberType is Nullable<Guid> and set the correct serializer for your scenario.

    Check out the following convention code:

    public class GuidAsStringRepresentationConvention : ConventionBase, IMemberMapConvention
    {
        public void Apply(BsonMemberMap memberMap)
        {
            if (memberMap.MemberType == typeof(Guid))
            {
                memberMap.SetSerializer(new GuidSerializer(BsonType.String));
            }
            else if (memberMap.MemberType == typeof(Guid?))
            {
                memberMap.SetSerializer(new NullableSerializer<Guid>(new GuidSerializer(BsonType.String)));
            }
        }
    }
    

    https://kevsoft.net/2020/06/25/storing-guids-as-strings-in-mongodb-with-csharp.html