如何告诉 MongoDB C# 驱动程序以字符串格式存储所有 Nullable<Guids>?

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

要将 Guid 序列化为字符串我没问题,因为我使用的是这段代码:

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

如果我尝试为 Guid 做同样的事情?没用

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

此行始终为空:

                var representationConfigurableSerializer = serializer as IRepresentationConfigurable;

你如何处理可为空的 Guid?

您需要重新配置当前的序列化程序还是可以直接替换它?更换它会更简单。

可空类型 BSON 序列化器被包装在装饰器序列化器类型 (NullableSerializer<>) 中,我们可以只检查 MemberTypeNullable<Guid> 并为您的场景设置正确的序列化器.

查看以下约定代码:

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