使用 C# 在 mongoDB 中存储具有多态值的字典

发布于 2024-12-16 00:24:07 字数 1823 浏览 1 评论 0原文

假设我们有一个键,其值在其意义上是多态的。考虑下一个示例项目:

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 为什么它不能正确映射它?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

霞映澄塘 2024-12-23 00:24:07

驱动程序应该了解所有鉴别器,以便无错误地反序列化任何类。有两种方法可以做到这一点:

1.在应用程序启动期间全局注册:

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

2.或者通过 BsonKnownTypes 属性:

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

 }

如果您使用#1或#2,您的反序列化将起作用正确。

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.

牵你手 2024-12-23 00:24:07

在尝试反序列化它们之前,您必须注册从 BaseClass 继承的类型。如果您首先序列化,这将自动发生,这可能就是错误仅有时发生的原因。

您可以使用属性注册派生类型:

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

public class DerivedType1 : BaseClass { ... }

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 { ... }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文