Serialize/Deserialize MongoDB Bson document using Official C# driver

隐身守侯 提交于 2019-12-14 02:44:59

问题


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; }
}

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".

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.

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


回答1:


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

BsonClassMap.RegisterClassMap<Dependent>();


来源:https://stackoverflow.com/questions/19954879/serialize-deserialize-mongodb-bson-document-using-official-c-sharp-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!