C# Driver serializing enums as ints in aggregation causing issues using LINQ lambdas

Following the topic: C# Driver serializing enums as ints in aggregation pipelines (but as strings everywhere else) - #6 by James_Kovacs

@James_Kovacs - Guys, I am experiencing the same bug after years of the following discussion above.

This is a part of my code:

Hi, @Volodymyr_Didukh,

Thanks for reaching out. In C#, enums are converted by the C# compiler to their underlying type, in this case an int. Our LINQ provider receives the AST (including the casts to int) and tries to undo them instead rendering the correct type - in this case a string - in the MQL.

You can view the MQL from the query by calling ToString() on the query or using the MongoDB Analyzer to view the MQL.

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using MongoDB.Driver.Linq;

var client = new MongoClient();
var db = client.GetDatabase("test");
var coll = db.GetCollection<Entity>("coll");

var query = coll.AsQueryable().Where(x => x.LanguageAsInt32 == Language.English && x.LanguageAsString == Language.English);
Console.WriteLine(query.ToString());


class Entity {
    public ObjectId Id { get; set; }
    public string Name { get; set; }
    public Language LanguageAsInt32 { get; set; }
    [BsonRepresentation(BsonType.String)]
    public Language LanguageAsString { get; set; }
}

enum Language {
    English = 42
}

Running this program with the .NET/C# Driver 3.1.0 results in the following output:

test.coll.Aggregate([{ "$match" : { "LanguageAsInt32" : 42, "LanguageAsString" : "English" } }])

Hopefully this helps.

Sincerely,
James