使用 C# 反序列化 MongoDB 中的接口 - 未知的鉴别器值 [英] Deserializing interface in MongoDB using C# - Unknown discriminator value
问题描述
首先,我使用当前版本的 MongoDB (3.2) 及其 C#-driver (2.2.3).我有以下课程:
First of all, I use the current version of MongoDB (3.2) and its C#-driver (2.2.3). I have the following classes:
public class Item
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
// ... some other properties
public Data Data { get; set; }
}
public class Data
{
public string BaseType { get; set; }
public IBaseData BaseData { get; set; }
}
public interface IBaseData
{
string Name { get; set; }
int Version { get; set; }
IDictionary<string, object> PayloadData { get; }
}
然后我有一些不同的 IBaseData 接口实现:
Then I have some different implementations of the IBaseData interface:
public class EventData : IBaseData
{
public int Version { get; set; }
public string Name { get; set; }
public IDictionary<string, object> PayloadData { get; set; }
public IDictionary<string, object> Properties { get; set; }
}
public class ExceptionData : IBaseData
{
// Implementation of the interface and some additional properties
}
将一个 Item-object 存储到 MongoDB 是没有问题的,看起来一切都是正确的.Mongo 使用 _t
来确定 IBaseData
的类型(例如 EventData
).当我第一次尝试检索数据时,它运行良好,这意味着我拥有完整的对象树.当我重新启动应用程序并再次发布相同的请求时,出现以下错误:
Storing an Item-object to MongoDB is no problem and it seems that everything is correct. Mongo uses the _t
to determine the type of IBaseData
(e.g. EventData
). When I try to retrieve the data for the first time, it works perfectly which means I have the complete tree of objects. When I restart the application and post the same request again, I get the following error:
反序列化类 Domain.Objects.Item 的 Data 属性时出错:反序列化类 Domain.Objects.Data 的 BaseData 属性时出错:未知鉴别器值EventData".
An error occurred while deserializing the Data property of class Domain.Objects.Item: An error occurred while deserializing the BaseData property of class Domain.Objects.Data: Unknown discriminator value 'EventData'.
删除 Mongo 数据库并启动应用程序后,它再次按预期工作.
After dropping the Mongo-database and starting the application, it works again as expected.
Google 给了我不同的方法,但没有任何帮助:
Google gave me different approaches but nothing helped me:
我想使用像 [BsonKnownTypes(typeof(Type1), typeof(Type2)]
这样的属性注释,但这仅适用于类.
I would like to work with property annotations like [BsonKnownTypes(typeof(Type1), typeof(Type2)]
, but this just works for classes.
你有什么想法吗?
推荐答案
我通过在 Program.cs(或其他应用程序启动类)中添加类映射为我部分解决了问题:
I partially solved the problem for me by adding a classmap in Program.cs (or other application-start class):
BsonClassMap.RegisterClassMap<EventData>(cm =>
{
cm.AutoMap();
cm.SetDiscriminator("EventData");
});
BsonClassMap.RegisterClassMap<ExceptionData>(cm =>
{
cm.AutoMap();
cm.SetDiscriminator("ExceptionData");
});
如果有人找到使用注释的方法,请回答这个问题.
If somebody find a way to work with annotations, please answer to this question.
这篇关于使用 C# 反序列化 MongoDB 中的接口 - 未知的鉴别器值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!