我觉得这是可能的,但我似乎无法找到它。我想配置我的mongo驱动程序,使任何DateTime
对象存储为BsonDocument。
mongo c#驱动程序允许您在全局设置某些约定,因此您不需要注释所有内容,这是否也适用于日期时间选项?
例如,我想删除以下注释:
[BsonDateTimeOptions(Representation = BsonType.Document)]
来自我的所有DateTime
媒体资源。有人能指出我正确的方向吗?
答案 0 :(得分:2)
当我尝试验证devshorts提供的答案是否有效时,我得到了一个编译时错误(因为集合初始化程序语法正在调用的ConventionPack的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);
答案 1 :(得分:0)
姗姗来迟,但答案是使用约定包并设置
ConventionRegistry.Register(
"Dates as utc documents",
new ConventionPack
{
new MemberSerializationOptionsConvention(typeof(DateTime), new DateTimeSerializationOptions(DateTimeKind.Utc, BsonType.Document)),
},
t => true);