Search code examples
mongodbbsonmongodb-.net-driver

Binary is not a valid representation for an ObjectIdSerializer


I'm trying to set the ObjectId from my TestObject class. The only problem is I keep getting exceptions and I have no way of debugging this serialization process.

My MongoDB:

{
    "_id" : LUUID("964c87a0-bf8a-1f4e-be85-7aadb5315adb")
}

An error has occurred while resolving 'MongoDataSource' data source: An error occurred while invaking data retrieval method.

--- InnerException ---

An error occurred while deserializing the Object property of class TestObject: Cannot deserialize a 'ObjectId' from BsonType 'Binary'.

--- InnerException ---

Cannot deserialize a 'ObjectId' from BsonType 'Binary'.

[DataObject]
public class TestObject
{
    [BsonId]
    [BsonElement("_id")]
    public ObjectId ObjectId { get; set; }
}

If I make it a BsonType.Binary

An error has occurred while resolving 'MongoDataSource' data source: An error occurred while invaking data retrieval method.

--- InnerException ---

Exception has been thrown by the target of an invocation.

--- InnerException ---

Binary is not a valid representation for an ObjectIdSerializer.

[DataObject]
public class TestObject
{
    [BsonId]
    [BsonElement("_id")]
    [BsonRepresentation(BsonType.Binary)]
    public ObjectId ObjectId { get; set; }
}

Solution

  • The problem is that the field inside Mongo collection is stored as LUUID (it's a GUID) that is a completely different type compared to an ObjectId.

    In your mapping class, you defined

    [DataObject]
    public class TestObject
    {
        [BsonId]
        [BsonElement("_id")]
        public ObjectId ObjectId { get; set; }
    }
    

    and when the driver tries to deserialize the value 964c87a0-bf8a-1f4e-be85-7aadb5315adb (string representation of a GUID) fails.

    Good news an id generator for GUID ships with the drivers and you can easily achieve the desired result just by following the driver's conventions:

    public class TestObject
    {
        public Guid Id { get; set; } // note the property is renamed in Id
    }
    

    As per official documentation you can omit [BsonId] [BsonElement("_id")] and [BsonId(IdGenerator = typeof(GuidGenerator))] attributes as long as the property is named Id and its type is one of the supported ones.