我在数据库中有一个收集事件的集合。每种类型的事件都有不同的数据集。我已经使用以下类定义了这个集合:
[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);
...I get mongo documents like
{
_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类型...无法映射到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"]
}
}
}
What I want, is the following result:
{
_id: ObjectId(...),
EventType: "JobQueued",
JobId: "job-123",
QueueName: "FastLane",
User: {
Name: "username",
Age: 10
},
JobParams : ["param-1", "param-2"]
}
有人知道如何实现吗?
(我正在使用C# mongodriver v2.3)