【发布时间】:2020-08-19 07:40:37
【问题描述】:
我有几个用接口标记的类。例如:
public class Example1 : IExample {}
public class Example2 : IExample {}
在我的大师班上,我有一个示例道具,但声明为接口。例如:
public class Master
{
public string Company { get; set; }
public IExample Examples { get; set; }
}
为了正常写入 Mongo,mongo 添加了一个 prop _t,其中包含由接口签名的类的名称,例如。示例 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 理解这个类?为什么插入有效?
我发现了类似这篇文章 (Deserialising polymorphic types with MongoDB C# Driver) 的其他帖子,但它们都在谈论基类而不是作为属性的接口。
按照检查过的帖子说的那样工作,但是我必须创建一个静态类,否则会抛出一个异常,说已经注册了。这是工作代码:
public class ClassMapRegisterer
{
static ClassMapRegisterer()
{
BsonClassMap.RegisterClassMap<Example1>();
}
public static void RegisterClassMaps()
{
}
}
在打开连接之前,只需输入:
ClassMapRegisterer.RegisterClassMaps();
干杯
【问题讨论】:
-
你能告诉我你正在使用的反序列化器吗?它有助于澄清错误的原因。
标签: c# mongodb interface deserialization mongodb-.net-driver