如何为MongoDb命名空间中的所有类注册ClassClassMap?
MongoDB驱动程序教程建议将类映射注册到automap via
BsonClassMap.RegisterClassMap();
我想自动化给定命名空间的所有类,而不是为每个类显式写下RegisterClassMap。 这目前可能吗?
你不需要写BsonClassMap.RegisterClassMap
,因为所有类都将默认自动化。
您需要自定义序列化时应使用RegisterClassMap
:
BsonClassMap.RegisterClassMap(cm => { cm.AutoMap(); cm.SetIdMember(cm.GetMemberMap(c => c.SomeProperty)); });
您还可以使用属性来创建管理序列化(它对我来说看起来更像是原生的):
[BsonId] // mark property as _id [BsonElement("SomeAnotherName", Order = 1)] //set property name , order [BsonIgnoreExtraElements] // ignore extra elements during deserialization [BsonIgnore] // ignore property on insert
您还可以创建在自动化期间使用的全局规则,如下所示:
var myConventions = new ConventionProfile(); myConventions.SetIdMemberConvention(new NoDefaultPropertyIdConvention()); BsonClassMap.RegisterConventions(myConventions, t => true);
我只使用属性和约定来管理序列化过程。
希望这有帮助。
作为基于约定的注册的替代方法,我需要使用一些自定义初始化代码为大量Type
s注册类映射,并且不希望为每种类型重复RegisterClassMap
。
根据KCD的注释,如果您需要显式注册类映射,如果需要反序列化多态类层次结构,则可以使用 BsonClassMap.LookupClassMap
,它将为给定的Type创建默认的AutoMapped注册。
但是,为了执行自定义映射初始化步骤,我需要求助于此hack,不幸的是LookupClassMap
在退出时冻结了映射,这阻止了对返回的BsonClassMap
进一步更改:
var type = typeof(MyClass); var classMapDefinition = typeof(BsonClassMap<>); var classMapType = classMapDefinition.MakeGenericType(type); var classMap = (BsonClassMap)Activator.CreateInstance(classMapType); // Do custom initialization here, eg classMap.SetDiscriminator, AutoMap etc BsonClassMap.RegisterClassMap(classMap);
上面的代码改编自BsonClassMap LookupClassMap
实现。