简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM