[CSHARP-1870] Comparisons in a LINQ Select projection should use the field serializer to serialize constants Created: 19/Dec/16  Updated: 04/Feb/22  Resolved: 04/Feb/22

Status: Closed
Project: C# Driver
Component/s: Linq, LINQ3
Affects Version/s: 2.1
Fix Version/s: 2.14.0

Type: Bug Priority: Minor - P4
Reporter: Robert Stam Assignee: James Kovacs
Resolution: Done Votes: 1
Labels: triaged
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Epic Link: CSHARP-3615

 Description   

When projecting a boolean value derived from comparing a field to a constant the constant should be serialized using the field's serializer.

One example showing why this is necessary is:

public enum E { A, B }
 
public class C
{
    public int Id { get; set; }
    [BsonRepresentation(BsonType.String)]
    public E E { get; set; }
}
 
public static class Program
{
    public static void Main(string[] args)
    {
        var client = new MongoClient("mongodb://localhost");
        var database = client.GetDatabase("test");
        var collection = database.GetCollection<C>("test");
 
        var queryable = collection.AsQueryable().Select(x => x.E == E.A);
        Console.WriteLine(queryable.ToString());
    }
}

The output is:

aggregate([{ "$project" : { "__fld0" : { "$eq" : ["$E", 0] }, "_id" : 0 } }])

but should be:

aggregate([{ "$project" : { "__fld0" : { "$eq" : ["$E", "A"] }, "_id" : 0 } }])

(i.e. "$E" should be compared to "A", not 0)



 Comments   
Comment by James Kovacs [ 04/Feb/22 ]

This issue has been fixed in the new LINQ provider (known as LINQ3), which is included in the 2.14 release.

Configure your MongoClientSettings to use LinqProvider.V3 if you want to use this functionality.

To configure a client to use the LINQ3 provider use code like the following

var connectionString = "mongodb://localhost";
var clientSettings = MongoClientSettings.FromConnectionString(connectionString);
clientSettings.LinqProvider = LinqProvider.V3;
var client = new MongoClient(clientSettings);

Generated at Wed Feb 07 21:40:54 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.