Trouble with MongoDB C# driver when performing queries using GuidRepresentation.Standard GuidSerializer

Viewed 1990

I am using the MongoDB C# driver version 2.11.0. I am aware of how GUIDs were handled differently by each driver in the past, and now there is a common standard. This isn't used by default in the C# driver for backwards compatibility reasons. The current recommendation seems to be to set the GuidRepresentation on the serializer. Either globally or for each mapped Guid property individually.

That's all fine, the problem I am facing is that queries against collections are not honoring the serialization settings, and only work properly when using the deprecated MongoDefaults setting. Documents are properly stored using the correct GuidRepresentation, but queries seem to attempt matching CSUUID rather than UUID, therefore it never matches with a document in the database.

Here's a basic class map:

public static void RegisterClassMaps()
{
    BsonClassMap.RegisterClassMap<Widget>(cm =>
    {
        cm.MapIdProperty(w => w.Id)
            .SetSerializer(new GuidSerializer(GuidRepresentation.Standard));
        cm.MapProperty(w => w.ParentId)
            .SetSerializer(new GuidSerializer(GuidRepresentation.Standard));
        cm.MapProperty(w => w.Name);
    }
}

And here's a simple query matching a Guid and a string. The following method will always return null, as it builds the query using CSUUID rather than UUID.

private readonly IMongoCollection<Widget> _collection;

public async Task<Widget> FindByNameAsync(Guid parentId, string name)
{
    var query = _collection.Find(w =>
        w.ParentId == parentId &&
        w.Name = name);
    return await query.SingleOrDefaultAsync();
}

Using AsQueryable() rather than Find() has the same result. Both build the query using CSUUID rather than UUID.

I also tried setting the global GuidSerializer to use GuidRepresentation.Standard, but I got the same results.

BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));

If I change the value of the deprecated MongoDefaults property, everything works perfectly fine.

MongoDefaults.GuidRepresentation = GuidRepresantion.Standard;

Am I missing something on how I am constructing my queries? I would prefer to avoid the deprecated setting.

2 Answers
BsonDefaults.GuidRepresentationMode = GuidRepresentationMode.V3;
BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));

BsonDefaults.GuidRepresentationMode is marked as deprecated because in a future version of the driver we will remove support for V2 mode and at that point we will also remove the GuidRepresentationMode property from BsonDefaults.

https://jira.mongodb.org/browse/CSHARP-3195

Related