JSON.NET cast error when serializing Mongo ObjectId

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; }
}

Leave a Comment