-
Type: Bug
-
Resolution: Fixed
-
Priority: Unknown
-
Affects Version/s: None
-
Component/s: None
-
None
-
Not Needed
-
Summary
An exception is thrown when performing an aggregate query containing a SortBy(), whose expression is a dictionary entry.
- This query works correctly with the V2 LinqProvider
- The exception is: MongoDB.Driver.Linq.ExpressionNotSupportedException "Expression must be a constant"
- The exception doesn't occur if the dictionary key is hard-coded to a constant value
- Tested with MongoDB.Driver v2.19.0
- I suspect this will also affect array indexes, as well as IndexKeysDefinitions
How to Reproduce
class Translation { public int Id { get; set; } public Dictionary<string, string>? Text { get; set; } } static List<Translation> GetSortedTranslations(IMongoCollection<Translation> collection, string language) { return collection.Aggregate() .SortBy(c => c.Text[language]) // This works in LinqProvider.V2, but not V3 .ToList(); } static List<Translation> GetTranslationsSortedByEnglish(IMongoCollection<Translation> collection) { return collection.Aggregate() .SortBy(c => c.Text["en"]) // This works .ToList(); }
Additional Background
The exception occurs when GetItemMethodToFilterFieldTranslator.TranslateWithStringIndex() calls indexExpression.GetConstantValue<string>(). GetConstantValue expects the expression to be of type ConstantExpression, whereas it is given a MemberAccess of a ConstantExpression. We may want to consider allowing partial execution, eg:
public static TValue GetConstantValue<TValue>(this Expression expression, Expression containingExpression) { if (expression is ConstantExpression constantExpression) { return (TValue)constantExpression.Value; } LambdaExpression lambda = Expression.Lambda(expression); Delegate fn = lambda.Compile(); return (TValue)fn.DynamicInvoke(null); }
- is duplicated by
-
CSHARP-4569 LINQ3 support for bracket notation on Exists Filter not working
- Closed
-
CSHARP-4577 LINQ3 provider throws ExpressionNotSupportedException when using Unset on a dictionary key
- Closed
- related to
-
CSHARP-4569 LINQ3 support for bracket notation on Exists Filter not working
- Closed
-
CSHARP-4574 Check whether we need to call EvaluatePartially in more places in LinqProviderAdapterV3
- Closed