在这种情况下,有两种可能性null
。您可能已经存储在实际null
在数据库:
{
_id:ObjectId(),
MyDateTime:null
}
,或者你不存储领域都:通过创建
{
_id:ObjectId()
}
在第一种情况下,你可以处理这个你自己的序列化程序:
public class DateTimeSerializer : BsonBaseSerializer
{
public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
{
var bsonType = bsonReader.CurrentBsonType;
switch (bsonType)
{
case BsonType.Null:
bsonReader.ReadNull();
return new DateTime();
case BsonType.DateTime:
return bsonReader.ReadDateTime();
default:
var message = string.Format("DateTimeSerializer needs a DateTime not {0}.", bsonType);
throw new BsonSerializationException(message);
}
}
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
{
if (value == null)
{
TimeSpan nowMs = DateTime.Now-new DateTime(1970,1,1);
bsonWriter.WriteDateTime((long)nowMs.TotalMilliseconds);
}
else
{
bsonWriter.WriteString((string)value);
}
}
}
(在这种情况下,给出当前日期,每当一个null
是序列化或反序列化)
你会那么需要注册为串行的DateTime类型:
BsonClassMap.RegisterClassMap<MyClass>(cm =>
{
cm.AutoMap();
cm.GetMemberMap(mc => mc.MyDateTime).SetSerializer(new DateTimeSerializer());
});
这不得不说,这将是更容易消毒的数据来源,所以它首先没有nulls
。
在第二种情况下,这已经通过MongoDB的C#的驱动程序,因为1.5处理,您使用的是哪个版本?您可以通过注册您自己的班级地图来设置默认值,如下所示,但如上所述,不再需要它。
BsonClassMap.RegisterClassMap<MyClass>(cm =>
{
cm.AutoMap();
cm.GetMemberMap(mc => mc.MyDateTime).SetDefaultValue(new DateTime());
});