我的数据库中有一个集合,我在其中记录事件。每种类型的事件都有不同的数据集。我用以下类定义了这一点:
[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获取芒果文档,如
{
_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# mongodriverv2.3)
发布于 2017-01-26 19:57:20
因此可以使用MongoDriver,因为它需要该类型的信息才值得返回。您可以做的是为用户类编写和注册自己的CustomMapper:
public class CustomUserMapper : ICustomBsonTypeMapper
{
public bool TryMapToBsonValue(object value, out BsonValue bsonValue)
{
bsonValue = ((User)value).ToBsonDocument();
return true;
}
}在开始计划的某个地方:
BsonTypeMapper.RegisterCustomTypeMapper(typeof(User), new CustomUserMapper());这将有效,我已经成功地序列化了您想要的数据。
但是:,当您想要反序列化它时,您将得到User类为Dictionary,因为驱动程序将没有关于如何反序列化它的信息:

https://stackoverflow.com/questions/41875032
复制相似问题