【发布时间】:2018-01-04 19:49:19
【问题描述】:
具有以下类:
public class Article
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Name { get; set; }
[BsonExtraElements()]
public Dictionary<string, Object> OtherData { get; set; }
}
我想将此对象添加到字典并写入数据库:
public class Bird
{
[BsonElement("_n")]
[BsonRequired]
public string Name { get; set; }
[BsonElement("_s")]
[BsonRequired]
public string Species { get; set; }
[BsonElement("_a")]
[BsonRequired]
public int Age { get; set; }
}
var col = db.GetCollection<Article>("articles");
var art = new Article
{
Name = "Blu"
};
art.OtherData = new System.Collections.Generic.Dictionary<string, object>()
{
{ "bird" , new Bird { Name = "Jerry", Age = 4, Species = "European starling" } }
};
col.InsertOne(art);
但是这会失败并出现以下异常:System.ArgumentException: '.NET type Bird cannot be mapped to a BsonValue'
如果我删除 [BsonExtraElements] 属性,一切都会正常,文章最终会进入数据库。为什么是这样?该属性如何防止序列化?因为属性不存在,所以我的这个自定义类可以被驱动序列化。
使用驱动程序版本 2.4.4
【问题讨论】:
-
我已经在 mongodb 的jira 上报告了这个。他们已经调查并回复:
It's not really intended behavior. We currently assume that all the values in the BsonExtraElements dictionary are either instances of BsonValue or trivially convertible to BsonValue. We should be able to convert more complex values like your Bird class by using a serializer. We will consider supporting this in a future release.
标签: c# mongodb dictionary bson