'Converting hardcoded Bson attributes to apply at startup in bulk

I have OPTION 0 which is working but I am trying to convert this to either OPTION 1 or 2, to clear my code from these default values but somehow I couldn't make it work. what am I doing wrong?

ERROR

MongoDB.Bson.BsonSerializationException: No matching creator found.

OPTION 0

public class Foo
{
    [BsonDefaultValue(null)]
    public Guid Id { get; private set; }

    [BsonDefaultValue(null)]
    public string Name { get; private set; }
}

OPTION 1

    private static Type CreateNewTypeWithAttribute(Type t)
    {
        var assemblyName = new AssemblyName(t.BaseType.BaseType.FullName);
        var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
        var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);
        var typeBuilder = moduleBuilder.DefineType(t.Name, TypeAttributes.Abstract | TypeAttributes.Sealed);

        var attrCtorParams = new Type[] { typeof(object) };
        var attrCtorInfo = typeof(BsonDefaultValueAttribute).GetConstructor(attrCtorParams);
        var attrBuilder = new CustomAttributeBuilder(attrCtorInfo, new object[] { null });

        foreach (PropertyInfo p in t.GetProperties())
        {
            var propertyBuilder = typeBuilder.DefineProperty(p.Name, PropertyAttributes.HasDefault, p.PropertyType, null);
            propertyBuilder.SetCustomAttribute(attrBuilder);
        }

        var newType = typeBuilder.CreateType();

        return newType;
    }

    private static void RegisterClassMap()
    {
        var types = GetTypes();
        types.ToList().ForEach(t=>
        {
            var newType = CreateNewTypeWithAttribute(t);

            BsonClassMap.LookupClassMap(newType);
        });
    }

OPTION 2

    private static void RegisterClassMap()
    {
        var pack = new ConventionPack();
        pack.Add(new DefaultNullPropertiesConvention());
        ConventionRegistry.Register("Conventions", pack, t => true);

        var types = GetTypes();
        types.ToList().ForEach(t=>
        {
            BsonClassMap.LookupClassMap(t);
        });
    }

    public class DefaultNullPropertiesConvention : IMemberMapConvention
    {
        public string Name => "default null properties for all classes";

        public void Apply(BsonMemberMap memberMap)
        {
            memberMap.ApplyDefaultValue(null);
        }
    }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source