问题是新驱动程序默认将字典序列化为文档。
MongoDB C# 驱动程序有 3 种方法来序列化字典:Document
、ArrayOfArrays
& ArrayOfDocuments
(更多内容请参见文档)。当它序列化为文档时,字典键是 BSON 元素的名称,它有一些限制(例如,如错误所示,它们必须序列化为字符串)。
在这种情况下,字典的键是DateTime
s ,它没有被序列化为字符串,但是作为Date
s 我们需要选择另一个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);