Juz*_*ott 0 c# reflection serialization mongodb
我有一个对象集合,每个对象都有一个属性 EventData,它有许多不同的类型。这些类型都继承自IEventData接口。
例如:
{ _id: '...', EventData: { _t: 'TypeA', ... } }
{ _id: '...', EventData: { _t: 'TypeB', ... } }
Run Code Online (Sandbox Code Playgroud)
我当前在尝试注册类映射时遇到 MongoDB C# 驱动程序的问题。当使用通用版本注册类映射时,EventData 对象使用所有属性和类型鉴别器正确序列化:
BsonClassMap.RegisterClassMap<TypeA>();
// Full event data is written to collection
// { _id: '...', EventData: { _t: 'TypeA', InterfaceProperty: '...', ClassProperty: '...' } }
Run Code Online (Sandbox Code Playgroud)
这工作正常,但是我有大量不同的事件类型,并且想要尝试使用一些反射来帮助自动化此操作。当尝试使用 RegisterClassMap 的非通用版本,同时迭代实现 IEventData 接口的所有类型时,只有接口成员被序列化:
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(i => i.GetTypes())
.Where(t => typeof(IEventData).IsAssignableFrom(t));
foreach (var type in types)
{
// If it's an interface, skip as we can't register those
if (type.IsInterface)
continue;
if (!BsonClassMap.IsClassMapRegistered(type))
BsonClassMap.RegisterClassMap(new BsonClassMap(type));
}
// Only the interface properties are written to collection
// { _id: '...', EventData: { _t: 'TypeA', InterfaceProperty: '...' } }
Run Code Online (Sandbox Code Playgroud)
使用非泛型类型注册允许将完整类型存储在集合中的类映射时,是否缺少某些属性或某些内容需要设置?
谢谢贾斯汀
两个变体之间的区别在于是否包含RegisterClassMap<T>()调用。AutoMap为了协调基于反射的方法与通用版本的调用,您可以将调用添加到AutoMap:
var cm = new BsonClassMap(type);
cm.AutoMap();
BsonClassMap.RegisterClassMap(cm);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
932 次 |
| 最近记录: |