db.requests.insert({
"_id" : "76f62a60-001b-11e6-8c47-02421d3a8dc5",
"controlnumber" : "2182048",
"created-date" : "Fri Mar 25 11:04:33 EDT 2016"
})
When i keep all the properties are of string then its working fine however i facing issue while taking CreatedDate as DateTime type.
Hi Rajendra,
If it’s possible, I would recommend to store the value of CreatedDate
in BSON Date UTC format instead of string.
Having said that, if you would like to map CreatedDate
from String to DateTime, you can try to use Serialization. Write a custom serialiser class inheriting SerializerBase.cs, to convert string to datetime (using DateTime ). For example:
class DateCreationSerializer : SerializerBase<DateTime>
{
public override DateTime Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
string stringdate = context.Reader.ReadString();
return DateTime.ParseExact(stringdate.Replace("EDT", "-07:00"), "ddd MMM d h:mm:s zzz yyyy", CultureInfo.InvariantCulture);
}
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, DateTime value)
{
context.Writer.WriteString(value.ToString("ddd MMM d h:mm:s EDT yyyy"));
}
}
You can then set the serialiser class when you register the mapping, as below:
BsonClassMap.RegisterClassMap<RequestModel>(map =>
{
map.AutoMap();
map.SetIgnoreExtraElements(true);
map.GetMemberMap(x => x.Id).SetElementName("_id");
map.GetMemberMap(x => x.ControlNumber).SetElementName("controlnumber"
);
map.GetMemberMap(x => x.CreatedDate).SetElementName("created-date").SetSerializer(new DateCreationSerializer());
});
Also see BsonSerializerTests.cs as a great reference of serialisation.
The above snippet was tested using MongoDB v3.2, .Net v4.5.2 and mongo-csharp-driver v2.2.x
You may also be interested to check out the TimeZone class to properly convert EDT.
Best Regards,
Wan.