Saving a dictionary with polymorphic values ​​in mongoDB using C #

Say we have a key with values ​​that are polymorphic in their own sense. Consider the following project example:

public class ToBeSerialized { [BsonId] public ObjectId MongoId; public IDictionary<string, BaseType> Dictionary; } 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<string, BaseType> { {"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<ToBeSerialized> mongoCollection = MongoDatabase.GetCollection<ToBeSerialized>("Dictionary"); mongoCollection.Save(objectToSave); ToBeSerialized received = mongoCollection.FindOne(); } } 

Sometimes, when I try to deserialize it, I get deserialization errors, such as β€œUnknown discriminator valueβ€œ Specific type name. ” What am I doing wrong? If each value stores _t, why can't it display it correctly?

+6
source share
2 answers

The driver must know about all discriminators to deserialize any class without errors. There are two ways to do this:

1. Register it worldwide at application launch time:

 BsonClassMap.RegisterClassMap<Type1>(); BsonClassMap.RegisterClassMap<Type2>(); 

2.Or, although BsonKnownTypes attibute:

 [BsonKnownTypes(typeof(Type1), typeof(Type2)] public class BaseType { } 

If you use # 1 or # 2, deserialization will work correctly.

+9
source

You need to register which types are inherited from BaseClass before trying to deserialize them. This will happen automatically if you serialize it first, which is probably why the error only occurs occasionally.

You can register derived types using the attribute:

 [BsonDiscriminator(Required = true)] [BsonKnownTypes(typeof(DerivedType1), typeof(DerivedType2))] public class BaseClass { ... } public class DerivedType1 : BaseClass { ... } 
+3
source

Source: https://habr.com/ru/post/901521/


All Articles