Dynamic variables are causing issues

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?

Hey @Steven_Rothwell, it looks like you’re using externalId to store values of different data types, which is why you’re resorting to using dynamic. Feel free to correct me if I’m mistaken. If my deduction is correct, could you consider modifying the schema to have multiple arrays, each with a specific data type? This might help you avoid using the dynamic type.

Thanks,
Mahi

Hey @Mahi_Satyanarayana, sorry yeah, I didn’t make it clear. The field name sent to the In(field, value) is not hardcoded in the code either. It figures out the name of the property and that is sent as the field, which is a string. The value is a string, but is converted to whatever type the property is. So, that’s why value is a dynamic type. It works just fine for all other types, except Guids.

Basically, it boils down to, the C# driver can handle dynamic value = Guid.Parse("6cd6f392-8271-49bb-8564-e584ddf48890"), but it cannot handle List<dynamic> value = new List<dynamic> { Guid.Parse("6cd6f392-8271-49bb-8564-e584ddf48890"), Guid.Parse("c7b1ebaf-4ac1-4fe0-b066-1282e072585a") }.

This issue is currently being looked into. There is a workaround here: https://jira.mongodb.org/browse/CSHARP-4784.