将所有日期存储为BsonDocuments
本文关键字:BsonDocuments 存储 日期 | 更新日期: 2023-09-27 18:06:27
我有一种感觉这是可能的,但我似乎找不到它。我想配置我的mongo驱动程序,使任何DateTime
对象存储为BsonDocument。
例如,我想删除以下注释:
[BsonDateTimeOptions(Representation = BsonType.Document)]
从我所有的DateTime
属性。有人能给我指个方向吗?
当我试图验证devshorts提供的答案是否有效时,我得到了一个编译时错误(因为由集合初始化器语法调用的convonpack的Add方法期望一个IConvention)。
建议的解决方案几乎正确,只需要稍微修改一下:
ConventionRegistry.Register(
"dates as documents",
new ConventionPack
{
new DelegateMemberMapConvention("dates as documents", memberMap =>
{
if (memberMap .MemberType == typeof(DateTime))
{
memberMap .SetSerializationOptions(new DateTimeSerializationOptions(DateTimeKind.Utc, BsonType.Document));
}
}),
},
t => true);
如果我们需要在多个地方使用这个约定,我们可以将它打包到一个类中,如下所示:
public class DateTimeSerializationOptionsConvention : ConventionBase, IMemberMapConvention
{
private readonly DateTimeKind _kind;
private readonly BsonType _representation;
public DateTimeSerializationOptionsConvention(DateTimeKind kind, BsonType representation)
{
_kind = kind;
_representation = representation;
}
public void Apply(BsonMemberMap memberMap)
{
if (memberMap.MemberType == typeof(DateTime))
{
memberMap.SetSerializationOptions(new DateTimeSerializationOptions(_kind, _representation));
}
}
}
然后像这样使用:
ConventionRegistry.Register(
"dates as documents",
new ConventionPack
{
new DateTimeSerializationOptionsConvention(DateTimeKind.Utc, BsonType.Document)
},
t => true);
姗姗来迟,但答案是使用约定包并设置
ConventionRegistry.Register(
"Dates as utc documents",
new ConventionPack
{
new MemberSerializationOptionsConvention(typeof(DateTime), new DateTimeSerializationOptions(DateTimeKind.Utc, BsonType.Document)),
},
t => true);