Darbio
Darbio

Reputation: 11418

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?

Upvotes: 4

Views: 3738

Answers (2)

Gabriel Weidmann
Gabriel Weidmann

Reputation: 887

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

Upvotes: 5

SJFJ
SJFJ

Reputation: 667

If you still experience this issue, write your own serializer. Have a look at the DateTimeOffsetSerializer MongoDB.Bson.Serialization.Serializers for implementation details. I actually use that instead of the default since it includes a readable DateTime. Register it this way:

new BsonStaticsWrapper().RegisterSerializer(typeof(DateTimeOffset), new DateTimeOffsetSerializer(BsonType.Document));

I know this isn't the exact answer to your question but it might help you get it. And it might help others in finding a workaround.

Upvotes: 2

Related Questions