具有以下类:BsonExtraElements字典<串,对象>和自定义类作为值失败序列
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类型鸟不能映射到BsonValue”
如果我删除[BsonExtraElements]
在致敬,一切顺利,文章在数据库中结束。为什么是这样?属性如何防止序列化?由于该属性不在那里,我的这个自定义类可以由驱动程序序列化。
使用驱动程序版本2.4.4
我报道这个在MongoDB的[JIRA ](https://jira.mongodb.org/browse/CSHARP-2035)。他们已经研究并回答:“这不是真正的预期行为。我们现在假设BsonExtraElements字典中的所有值都是BsonValue的实例,或者可以简单地转换为BsonValue。我们应该能够通过使用序列化器来转换更复杂的值,比如您的Bird类。 我们会考虑在未来的版本中支持这个.' –