Storing a Dictionary with polymorphic values in mongoDB using C#

眉间皱痕 提交于 2019-11-30 04:56:40

问题


Let us say we have a key with values which are polymorphic in their sense. Consider the next sample project:

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 like "Unknown discriminator value 'The name of concrete type'". What am I doing wrong? If every value stores a _t why cannot it map it correctly?


回答1:


Driver should know about all discriminators to deserialize any class without errors. There are two ways to do it:

1.Register it globally during app start:

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

2.Or though the BsonKnownTypes attibute:

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

 }

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




回答2:


You have to register which types inherit from BaseClass before attempting to deserialize them. This will happen automatically if you serialize first, which is probably why the error occurs only sometimes.

You can register derived types using an attribute:

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

public class DerivedType1 : BaseClass { ... }


来源:https://stackoverflow.com/questions/8138330/storing-a-dictionary-with-polymorphic-values-in-mongodb-using-c-sharp

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