I’m using MongoDB.Driver 2.21.0 in my .NET 7 API. I am trying to use reflection to dynamically return data. For the most part, it works great. I’ve been able to dynamically query on strings and ints without issue. But, when I query with Guids, I start getting errors.
In my Program.cs, I have the following code:
BsonDefaults.GuidRepresentationMode = GuidRepresentationMode.V3;
BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));
Although my code is doing things dynamically, I’ve hardcoded a filter in to narrow down the issue. If I use this filter:
var filter = Builders<BsonDocument>.Filter.In("externalId", new List<dynamic> { Guid.Parse("6cd6f392-8271-49bb-8564-e584ddf48890"), Guid.Parse("c7b1ebaf-4ac1-4fe0-b066-1282e072585a") });
I get this error:
MongoDB.Bson.BsonSerializationException: GuidSerializer cannot serialize a Guid when GuidRepresentation is Unspecified.
Even though it is specified in the Program.cs. But, if I make the List, it works perfectly fine and returns the expected data.
var filter = Builders<BsonDocument>.Filter.In("externalId", new List<Guid> { Guid.Parse("6cd6f392-8271-49bb-8564-e584ddf48890"), Guid.Parse("c7b1ebaf-4ac1-4fe0-b066-1282e072585a") });
Since, in my code requires dynamic since I don’t know the type until runtime, is there a suggested work-around for this?