使用官方C#驱动程序序列化/反序列化MongoDB Bson文档 [英] Serialize/Deserialize MongoDB Bson document using Official C# driver

查看:537
本文介绍了使用官方C#驱动程序序列化/反序列化MongoDB Bson文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用MongoDB的官方C#驱动程序开发MongoDB. 我有以下类/接口定义:

I recently started working on MongoDB using the official C# driver for MongoDB. I have the following class/interface definitions:

public interface IDependent {
   int Index { get; set; }
   string Name { get; set; }
}

public class Person {
   int Id { get; set; }
   string Name {get; set; }
   IDependent[] Dependents { get; set; }
}
public class Dependent : IDependent {
    int Index {get; set; }
    string Name { get; set; }
}

使用此类/接口结构,将Person记录与IDependent作品数组一起插入.但是,当我尝试检索Person对象时,mongoDB C#驱动程序会抱怨"IDependent的未知标识符".

Using this class/interface structure, inserting Person record with an array of IDependent works. But when I try to retrieve the Person object, the mongoDB C# driver complains of "Unknown Discriminator for IDependent".

如果我的理解是正确的,则反序列化器无法确定必须为Dependents数组中的每个元素创建其实例的类类型.

If my understanding is correct, the Deserializer is unable to determine the class type whose instance it has to create for each element in the Dependents array.

如何将IDependent的类类型映射为Dependent,以便mongoDB驱动程序可以对其进行反序列化?

How do I map that the class type for IDependent is Dependent, so that the mongoDB driver can deserialize it properly?

推荐答案

我知道了.我要做的就是注册Dependent类,它的工作方式与

I figured this out. All I had to do was to register the Dependent class and it works as in

BsonClassMap.RegisterClassMap<Dependent>();

这篇关于使用官方C#驱动程序序列化/反序列化MongoDB Bson文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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