问题
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