使用C#存储与多态值的字典在MongoDB中 [英] Storing a Dictionary with polymorphic values in mongoDB using C#

查看:1277
本文介绍了使用C#存储与多态值的字典在MongoDB中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我们有这是在他们的意识多态值的键。考虑下一个示例项目:

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



有时,当我尝试反序列化,我得到反序列化错误例如未知的鉴别值具体类型的名字'。我在做什么错了?如果每个值存储_t为什么不能正确映射呢?

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?

推荐答案

驾驶员应了解所有鉴别反序列化没有错误的任何类。有两种方法可以做到这一点:

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

1.注册它在全球范围内启动的应用程序:

1.Register it globally during app start:

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



2.Or虽然的 BsonKnownTypes attibute:

2.Or though the BsonKnownTypes attibute:

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

 }

如果您将使用#1或#2你的反序列化将正常工作。

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

这篇关于使用C#存储与多态值的字典在MongoDB中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆