【问题标题】:Passing Type information to MongoDB so it can deserialize interface types properly?将类型信息传递给 MongoDB,以便它可以正确反序列化接口类型?
【发布时间】:2016-04-04 20:12:03
【问题描述】:

我有一个作为BsonDocument 序列化到MongoDB 中的类,这个类也恰好有一个IMyInterface 类型的属性。

public interface IMyInterface
{
    String Name { get; set; }
}

public class MyClass
{
    public IMyInterface IntRef { get; set; }
}

MyClass 对象实例的生命周期内,IntRef 可以引用多个实现IMyInterface 的不同类。序列化后,我发现IntRef 指向的类中的所有数据也在BsonDocument 中序列化,而不仅仅是Name

在反序列化时,尽管BsonDocument.Deserialize 没有关于IntRef 指向的类的Type 的信息并引发异常。 我如何在拨打Deserialize 时提供Type 信息?

我也有一个幼稚的工作,我在DeserializeIntRef 的文档部分,效果很好。给定正确的类TypeBsonDocument.Deserialize 返回该Type 的对象实例。虽然这里的问题是我仍然不能Deserialize 顶级BsonDocument 代表MyClass,因为它仍然包含与IntRef 有关的子文档。 有没有办法告诉Deserialize 忽略BsonDocument 的一部分? 我的想法是设置MyBsonDocument[SubDocName] = null,尽管它不可​​为空。

【问题讨论】:

  • 我自己对 Mongo 和 BsonDocument 的经验有限,但由于您没有回复,您看到 this SO question 了吗?
  • 嗯。我猜它很接近,尽管这是不序列化对象的某些部分,而不是不反序列化它。虽然......我认为ClassMap 可能是答案的一部分。我将不得不调查它,我从未见过。

标签: c# mongodb serialization bson


【解决方案1】:

由于MyClass 指向一个接口类型,然后它可以保存任何实现该接口的类' Bson,我们必须告诉 MongoDB 类的类型'可以在最后(所有) 界面。然后它可以从类中推断出它知道如何反序列化包含这些类的 Bson 的某些 BsonDocuments

public interface IMyInterface
{
    String Name { get; set; }
}

public class MyIntImpl : IMyInterface
{
    public String Name { get; set; }
}

public class MyClass
{
    public IMyInterface IntRef { get; set; }

    public MyClass()
    {
        IntRef = new MyIntImpl();
    }
}

// When starting up MongoDB
private void RegisterClasses()
{
    BsonClassMap.RegisterClassMap<MyIntImpl>();
}

通过将MyIntImpl 类添加到 BsonClassMap,它现在知道如何从该类类型反序列化 Bson。您只需要确保您的地图中充满了实现您可能会序列化的接口的类。

一些参考链接:High to low level overview of C# MongoDB serializationan SO post 概述了解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-20
    • 2020-10-27
    • 2014-07-01
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    相关资源
    最近更新 更多