.Net MongoDB 基于接口反序列化 prop

.Net MongoDB Deserialising prop based in an Interface

我有几个 class 带有接口标记。例如:

public class Example1 : IExample {}

public class Example2 : IExample {}

在我的 master class 上,我有一个 Example 的 prop 但声明为 Interface。例如:

public class Master
{
  public string Company { get; set; }

  public IExample Examples { get; set; }
}

为了写入 Mongo 工作正常,mongo 添加了一个 prop _t,它具有由接口签名的 class 的名称,例如。示例 1 或示例 2

但是反序列化根本不起作用。抛出错误:

Exception thrown: 'System.FormatException' in MongoDB.Bson.dll: 'An error occurred while deserializing the Source property of class Audit.Processed: Unknown discriminator value 'Example1'.'

我是否必须注册某些东西或将某些东西的某些属性添加到 Mongo 理解这个 class?为什么插入有效?

我发现其他 post 与此类似 (Deserialising polymorphic types with MongoDB C# Driver),但他们都谈论基础 classes 而不是作为 属性 的接口.

按照检查的 post 所说的那样工作,但我必须创建一个静态 class,否则会抛出一个异常,说明已注册。这是工作代码:

public class ClassMapRegisterer
{
    static ClassMapRegisterer()
    {
        BsonClassMap.RegisterClassMap<Example1>();
    }

    public static void RegisterClassMaps()
    {            
    }
}

在打开连接之前,只需输入:

ClassMapRegisterer.RegisterClassMaps();

干杯

根据documentation

If you ever see an error message about an “Unknown discriminator”, it is because the deserializer can’t figure out the class for that discriminator. If you are mapping your classes programmatically simply make sure that all classes in the hierarchy have been mapped before beginning deserialization.

您不能使用 BsonKnowTypes 属性,因为当您有接口时它仅限于类和结构,但您可以使用 RegisterClassMap:

BsonClassMap.RegisterClassMap<Example1>();
BsonClassMap.RegisterClassMap<Example2>();