Deserialising多态类型的MongoDB的C#驱动程序 [英] Deserialising polymorphic types with MongoDB C# Driver

查看:267
本文介绍了Deserialising多态类型的MongoDB的C#驱动程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设,我有一个基类

public class Node{
    public ObjectId Id;
    public String nodeName;
    public ObjectId parentNode;
}

和2派生类

public class PlotNode:Node{
    public ObjectId Id;
    public String plotDetail;
}

public class EndNode:Node{
    public ObjectId Id;
    public int resultCode;
}

所有3班的几个对象序列化是在数据库中。

Several objects of all 3 classes are serialized are in database.

和唯一的数据我已经是的ObjectId的名单,只知道这些IDS的事情是,他们肯定是节点ID,但它不知道他们是否是节点,PlotNode或终端节点在deserialise时间

And only data i have is a list of ObjectId's, and only thing known about these ids is that they are certain to be Node ids but it's not know whether they are Node,PlotNode or EndNode in deserialise time.

我用这来反序列化:

var collection = db.GetCollection<Node>("nodes");
var query = Query<Node>.EQ(e => e.Id, id);
Node node = collection.FindOne(query);



而在最后我得到的节点,而不是实际的PlotNodes或EndNodes。

And in the end i get Nodes, not actual PlotNodes or EndNodes.

我怎么能知道,如果他们是派生类型之一,并取回该类型的对象呢?

How can i know if they are one of the derived types and get back a object of that type?

推荐答案

为什么你有相同的大众的ObjectId标识;在每一个派生类?
这是不是真的好主意。它隐藏父ID字段。

Why do you have the same "public ObjectId Id;" in each derived class? It is not really good idea. It hides parent Id field.

要解决你的问题,你需要注册你的派生类(如在任何序列化/反序列化机制)。
有3种方法来做到这一点:

To solve your problem you need to "register" your derived classes (like in any serialization/deserialization mechanism). There are 3 ways to do it:


  1. 声明的方式 - 装点基本节点类:

  1. Declarative way - decorate base Node class with:

[BsonKnownTypes(typeof(PlotNode), typeof(EndNode))]


  • 通用的方法 - 当类型在编译时是已知的:

  • Generic way - when types are known at compile time:

    BsonClassMap.RegisterClassMap<PlotNode>();
    BsonClassMap.RegisterClassMap<EndNode>();
    


  • 动态的方式 - 当类型是在编译时未知:

  • Dynamic way - when types are unknown at compile time:

    BsonClassMap.LookupClassMap(typeof(PlotNode));
    BsonClassMap.LookupClassMap(typeof(EndNode));
    





    • 另一个建议的 - 的使用LINQ,而不是查询

      Node node = collection.AsQueryable().FirstOrDefault(n => n.Id == id);
      


    • 这篇关于Deserialising多态类型的MongoDB的C#驱动程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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