JSON.NET cast error when serializing Mongo ObjectId

后端 未结 6 1240
旧巷少年郎
旧巷少年郎 2020-11-28 09:36

I am playing around with MongoDB and have an object with a mongodb ObjectId on it. When I serialise this with the .NET Json() method, all is good (but the dates are horrible

6条回答
  •  独厮守ぢ
    2020-11-28 09:43

    You can use .NET string type instead of ObjectId, You just need to decorate it with BsonRepresentation. If you use BsonDateTime, you will have the same conversion issue. This is a domain class in my project that uses those decorators.

    public class DocumentMetadata
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
        public string Name { get; set; }
        public string FullName { get; set; }
    
        [BsonDateTimeOptions(Kind = DateTimeKind.Utc)]
        public DateTime DownloadTime { get; set; }
    }
    

提交回复
热议问题