问题是新驱动程序默认将字典序列化为文档。
MongoDB C# 驱动程序有 3 种方法来序列化字典:Document
, ArrayOfArrays
& ArrayOfDocuments
(文档中有更多相关内容 http://mongodb.github.io/mongo-csharp-driver/2.2/reference/bson/mapping/#dictionary-serialization-options)。当它序列化为文档时,字典键是 BSON 元素的名称,它有一些限制(例如,正如错误所示,它们必须序列化为字符串)。
在这种情况下,字典的键是DateTime
s 没有序列化为字符串,而是序列化为Date
所以我们需要选择另一个DictionaryRepresentation
.
要更改此特定属性的序列化,我们可以使用BsonDictionaryOptions
具有不同的属性DictionaryRepresentation
:
[BsonDictionaryOptions(DictionaryRepresentation.ArrayOfArrays)]
public Dictionary<DateTime, int> Dictionary { get; private set; }
但是,我们需要对每个有问题的成员单独执行此操作。要应用此DictionaryRepresentation
对于所有相关成员,我们可以实施一项新公约:
class DictionaryRepresentationConvention : ConventionBase, IMemberMapConvention
{
private readonly DictionaryRepresentation _dictionaryRepresentation;
public DictionaryRepresentationConvention(DictionaryRepresentation dictionaryRepresentation)
{
_dictionaryRepresentation = dictionaryRepresentation;
}
public void Apply(BsonMemberMap memberMap)
{
memberMap.SetSerializer(ConfigureSerializer(memberMap.GetSerializer()));
}
private IBsonSerializer ConfigureSerializer(IBsonSerializer serializer)
{
var dictionaryRepresentationConfigurable = serializer as IDictionaryRepresentationConfigurable;
if (dictionaryRepresentationConfigurable != null)
{
serializer = dictionaryRepresentationConfigurable.WithDictionaryRepresentation(_dictionaryRepresentation);
}
var childSerializerConfigurable = serializer as IChildSerializerConfigurable;
return childSerializerConfigurable == null
? serializer
: childSerializerConfigurable.WithChildSerializer(ConfigureSerializer(childSerializerConfigurable.ChildSerializer));
}
}
我们注册如下:
ConventionRegistry.Register(
"DictionaryRepresentationConvention",
new ConventionPack {new DictionaryRepresentationConvention(DictionaryRepresentation.ArrayOfArrays)},
_ => true);