让我们说我们有一个关键值,它们的意义上是多态的.考虑下一个示例项目:
public class ToBeSerialized { [BsonId] public ObjectId MongoId; public IDictionaryDictionary; } public abstract class BaseType { } public class Type1 : BaseType { public string Value1; } public class Type2:BaseType { public string Value1; public string Value2; } internal class Program { public static void Main() { var objectToSave = new ToBeSerialized { MongoId = ObjectId.GenerateNewId(), Dictionary = new Dictionary { {"OdEd1", new Type1 {Value1="value1"}}, { "OdEd2", new Type1 {Value1="value1"} } } }; string connectionString = "mongodb://localhost/Serialization"; var mgsb = new MongoUrlBuilder(connectionString); var MongoServer = MongoDB.Driver.MongoServer.Create(mgsb.ToMongoUrl()); var MongoDatabase = MongoServer.GetDatabase(mgsb.DatabaseName); MongoCollection mongoCollection = MongoDatabase.GetCollection ("Dictionary"); mongoCollection.Save(objectToSave); ToBeSerialized received = mongoCollection.FindOne(); } }
有时当我尝试反序列化它时,我会得到反序列化错误,例如"Unknown discriminator value'具体类型的名称'".我究竟做错了什么?如果每个值存储_t为什么它不能正确映射?
驱动程序应该知道所有鉴别器以反序列化任何类而不会出错.有两种方法可以做到:
1.在应用启动期间全局注册:
BsonClassMap.RegisterClassMap(); BsonClassMap.RegisterClassMap ();
2.Or虽然BsonKnownTypes attibute:
[BsonKnownTypes(typeof(Type1), typeof(Type2)] public class BaseType { }
如果您将使用#1或#2,则反序列化将正常工作.