使用 C# 从 MongoDB 获取继承的实例
我正在使用官方 MongoDb C# 驱动程序。
我的场景:我将对象存储到 MongoDb 中。所有对象都是从同一根类继承的类的实例。 在设计时,我不知道可以存储的所有类(即它们可以插入) - 因此我需要某种方法来告诉序列化器/驱动程序如何将类映射到文档(文档中的鉴别器)。
有人有什么想法吗?
I'm using the official MongoDb C# driver.
My scenario: I store objects into MongoDb. All objects are instances of classes that inherit from the same root class.
At design time I do not know all classes that can be stored (i.e they can be plugged in) - so I need some way to tell the serializer/driver how to map the classes to documents (descriminators in the document).
Anyone got any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
每当对象的实际类型与名义类型不同时,官方 C# 驱动程序就会写入“_t”鉴别器值。例如:
Insert 语句也可以这样写:
但让编译器推断类型参数更容易。
由于 obj 的实际类型与标称类型不同,因此将写入“_t”鉴别符。
读回对象时,您必须确保 MyDerivedClass 已正确注册:
否则序列化器将无法识别鉴别器(这可能看起来像是一个限制,但序列化器只能使用它知道的类型是合乎逻辑的) 。
您提到您在编译时不知道这些类,因此必须动态调用上述注册代码。一种方法是:
从技术上讲,序列化不使用反射;它是元数据驱动的。使用一次反射来构造类映射,之后直接使用类映射而无需反射,开销相当低。
The official C# driver will write a "_t" discriminator value whenever the actual type of an object is different than the nominal type. So for example:
The Insert statement could also have been written:
but it's easier to let the compiler infer the type parameter.
Since the actual type of obj is different than the nominal type the "_t" discriminator will be written.
When reading back the object you will have to ensure that MyDerivedClass has been properly registered:
or the serializer won't recognize the discriminator (this may seem like a restriction, but it's only logical that the serializer can only work with types it knows about).
You mentioned that you don't know the classes at compile time, so the above registration code must be invoked dynamically. One way to do it is:
Technically, the serialization is not using reflection; it is metadata driven. Reflection is used once to construct the class map, but after that the class map is used directly without reflection, and the overhead is rather low.
我编写了一个辅助类,改进了 Robert Stam 的出色答案,并允许使用与静态 BsonClassMap.RegisterClassMap<...>() 方法相同的参数。
现在,我可以使用与已知类型几乎相同的语法来注册编译时未知的类型:
或者
这些方法应该在 C# 驱动程序中可用。
I wrote an helper class improving the excellent answer of Robert Stam and allowing the same parameters as the static BsonClassMap.RegisterClassMap<...>() method.
Now I am able to register a type that was unknown at compile time with almost the same syntax as a known one:
or
These methods should be available in the C# driver.
请在此处查看驱动程序序列化文档。
Take a look into driver serialization documentation here.