。基于接口的.Net MongoDB反序列化道具

问题描述 投票:2回答:1

我有几个用接口标记的类。例如:

public class Example1 : IExample {}

public class Example2 : IExample {}

在我的主类上,我有一个Example实例,但声明为Interface。例如:

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

  public IExample Examples { get; set; }
}

要写给Mongo,它工作正常,mongo添加一个prop _t,其名称由接口(例如,接口)签名。 Example1或Example2

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

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理解此类?为什么插入有效?

我发现了其他类似这样的文章(Deserialising polymorphic types with MongoDB C# Driver,但是他们都谈论基类而不是接口作为属性。

欢呼声

c# mongodb interface deserialization mongodb-.net-driver
1个回答
0
投票

根据documentation

[如果您看到有关“未知标识符”的错误消息,那是因为解串器无法找出该标识符的类。如果要以编程方式映射类,只需在开始反序列化之前确保已映射层次结构中的所有类。

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

BsonClassMap.RegisterClassMap<Example1>();
BsonClassMap.RegisterClassMap<Example2>();
© www.soinside.com 2019 - 2024. All rights reserved.