Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB C# DateTimeOffset serialization

I'm storing a DateTimeOffset in a Mongo DB using the standard serialization providers.

In the database it looks like this:

{
    "_id" : LUUID("1197f7cf-cb83-4047-85f8-6e9f8c8ad24f"),
    "CreatedDateTimeUtc" : [ 
        6.3612613922066e+017.0, 
        0
    ]
}

But when I try and deserialize in C# the following exception is thrown:

System.FormatException: An error occurred while deserializing the CreatedDateTimeUtc property of class Turnout.Common.Model.Turnout: ReadInt64 can only be called when CurrentBsonType is Int64, not when CurrentBsonType is Double.

Any ideas on how to get it to play nicely?

like image 936
Darbio Avatar asked Nov 16 '25 21:11

Darbio


1 Answers

In the modern ages MongoDB made this a lot easier 😉

BsonSerializer.RegisterSerializer(typeof(DateTimeOffset), new DateTimeOffsetSerializer(BsonType.DateTime));

Afterwards your db entities will have DateTimeOffset serialized like this:

CreatedAt: 2012-01-26T12:15:55.000+00:00
like image 64
Gabriel Weidmann Avatar answered Nov 18 '25 10:11

Gabriel Weidmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!