【发布时间】:2017-06-12 00:24:31
【问题描述】:
我的数据库中有一个用于记录事件的集合。每种类型的事件都有一组不同的数据。我用以下类定义了它:
[CollectionName("LogEvent")]
public class LogEvent
{
public LogEvent(string eventType)
{
EventType = eventType;
EventData = new Dictionary<string, object>();
}
public string EventType { get; private set; }
[BsonExtraElements]
public IDictionary<string, object> EventData { get; private set; }
}
现在 - 这在某种程度上非常有效。只要EventData字典的元素是简单类型...
var event = new LogEvent("JobQueues"){
EventData = new Dictionary<string, object>(){
{ "JobId": "job-123" },
{ "QueueName": "FastLane" }
}
}
_mongoCollection.InsertOne(event);
...我得到类似的 mongo 文档
{
_id: ObjectId(...),
EventType: "JobQueued",
JobId: "job-123",
QueueName: "FastLane"
}
但是,一旦我尝试向字典中添加自定义类型,事情就会停止工作。
var event = new LogEvent("JobQueues"){
EventData = new Dictionary<string, object>(){
{ "JobId": "job-123" },
{ "QueueName": "FastLane" },
{ "JobParams" : new[]{"param-1", "param-2"}},
{ "User" : new User(){ Name = "username", Age = 10} }
}
}
这给了我像".NET type ... cannot be mapped to BsonType."这样的错误
如果我删除 [BsonExtraElements] 标记和 [BsonDictionaryOptions(DictionaryRepresentation.Document)] 它将开始序列化内容而不会出错,但它会给我一个完全不同的文档,我不喜欢..
{
_id: ObjectId(...),
EventType: "JobQueued",
EventData: {
JobId: "job-123",
QueueName: "FastLane",
User: {
_t: "User",
Name: "username",
Age: 10
},
JobParams : {
_t: "System.String[]",
_v: ["param-1", "param-2"]
}
}
}
我想要的是以下结果:
{
_id: ObjectId(...),
EventType: "JobQueued",
JobId: "job-123",
QueueName: "FastLane",
User: {
Name: "username",
Age: 10
},
JobParams : ["param-1", "param-2"]
}
有人知道如何实现吗?
(我使用的是 C# mongodriver v2.3)
【问题讨论】:
标签: c# .net mongodb serialization mongodb-.net-driver