如何为MongoDb的名称空间中的所有类注册ClassMap? [英] How to RegisterClassMap for all classes in a namespace for MongoDb?

查看:339
本文介绍了如何为MongoDb的名称空间中的所有类注册ClassMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MongoDB驱动程序指南建议将类映射注册为自动映射通过

The MongoDB driver tutorial suggests to register class maps to automap via

BsonClassMap.RegisterClassMap<MyClass>();

我想自动映射给定名称空间的所有类,而无需为每个类显式写下RegisterClassMap.目前有可能吗?

I would like to automap all classes of a given namespace without explicitly writing down RegisterClassMap for each class. Is this currently possible?

推荐答案

您不需要写BsonClassMap.RegisterClassMap<MyClass>();,因为默认情况下所有类都将自动映射.

You don't need write BsonClassMap.RegisterClassMap<MyClass>();, because all classes will be automapped by default.

需要自定义序列化时应使用RegisterClassMap:

You should use RegisterClassMap when you need custom serialization:

 BsonClassMap.RegisterClassMap<MyClass>(cm => {
        cm.AutoMap();
        cm.SetIdMember(cm.GetMemberMap(c => c.SomeProperty));
    });

您还可以使用属性来创建管理序列化(对我来说,本机看起来更原生):

Also you can use attributes to create manage serialization(it's looks like more native for me):

[BsonId] // mark property as _id
[BsonElement("SomeAnotherName", Order = 1)] //set property name , order
[BsonIgnoreExtraElements] // ignore extra elements during deserialization
[BsonIgnore] // ignore property on insert

您还可以创建在自动映射过程中使用的全局规则,如下所示:

Also you can create global rules thats used during automapping, like this one:

var myConventions = new ConventionProfile();
myConventions.SetIdMemberConvention(new NoDefaultPropertyIdConvention());
BsonClassMap.RegisterConventions(myConventions, t => true);

我仅使用属性和约定来管理序列化过程.

I am using only attributes and conventions to manage serialization process.

希望获得帮助.

这篇关于如何为MongoDb的名称空间中的所有类注册ClassMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆