{"record":{"id":"4c20e8cb8e2e777f","repo":"litedb-org/LiteDB","slug":"invalid-bsonexpression-when-converted-from-linq-ex","errorCode":null,"errorMessage":"Invalid BsonExpression when converted from Linq expression: {_expr.ToString()} - `{expression}`","messagePattern":"Invalid BsonExpression when converted from Linq expression: (.+?) - `(.+?)`","errorType":"exception","errorClass":"NotSupportedException","httpStatus":null,"severity":"error","filePath":"LiteDB/Client/Mapper/Linq/LinqExpressionVisitor.cs","lineNumber":88,"sourceCode":"            var expression = _builder.ToString();\n\n            try\n            {\n                var e = BsonExpression.Create(expression, _parameters);\n\n                // if expression must return an predicate but expression result is Path/Parameter/Call add `= true`\n                if (predicate && (e.Type == BsonExpressionType.Path || e.Type == BsonExpressionType.Call || e.Type == BsonExpressionType.Parameter))\n                {\n                    expression = \"(\" + expression + \" = true)\";\n\n                    e = BsonExpression.Create(expression, _parameters);\n                }\n\n                return e;\n            }\n            catch (Exception ex)\n            {\n                throw new NotSupportedException($\"Invalid BsonExpression when converted from Linq expression: {_expr.ToString()} - `{expression}`\", ex);\n            }\n        }\n\n        /// <summary>\n        /// Visit :: `x => x.Customer.Name`\n        /// </summary>\n        protected override Expression VisitLambda<T>(Expression<T> node)\n        {\n            var l = base.VisitLambda(node);\n\n            // remove last parameter $ (or @)\n            _builder.Length--;\n\n            return l;\n        }\n\n        /// <summary>\n        /// Visit lambda invocation","sourceCodeStart":70,"sourceCodeEnd":106,"githubUrl":"https://github.com/litedb-org/LiteDB/blob/f906a5f850678719e39a39a006cb66dcae563cfa/LiteDB/Client/Mapper/Linq/LinqExpressionVisitor.cs#L70-L106","documentation":"A catch-all thrown by LinqExpressionVisitor.Resolve when BsonExpression.Create fails to parse the string that the visitor built from the LINQ expression. The visitor translated the expression tree into a BsonExpression string, but that string is syntactically or semantically invalid. The original LINQ expression and the generated string are both included to aid debugging, and the original parse exception is passed as the inner exception.","triggerScenarios":"Any LINQ expression whose translation produces a BsonExpression string that BsonExpression.Create cannot parse. This is the fallback for constructs that pass individual Visit stages but combine into an invalid final expression. The inner exception holds the precise tokenizer/parse error.","commonSituations":"Complex nested expressions (e.g., combining unsupported method chains with binary operators) that partially translate but produce malformed output. Using LINQ constructs at the edge of the translator's supported surface that yield a near-valid but ultimately unparseable BsonExpression string. Version differences where a construct worked before but the translation changed.","solutions":["Read the inner exception (ex.InnerException) for the exact token/parse error and the generated BsonExpression string to pinpoint the bad fragment.","Simplify the LINQ expression incrementally to isolate which sub-expression produces the invalid output.","Replace the failing LINQ predicate with a raw BsonExpression string via Query.Where() or the string-based Find overload.","Check LiteDB release notes for known translation gaps and supported LINQ surface."],"exampleFix":"// before -- complex LINQ that fails translation\nvar results = col.Find(x => x.Items.Select(i => i.Price * i.Qty).Sum() > 100);\n\n// after -- use a raw BsonExpression string\nvar results = col.Find(\"MAP($.Items[*], @0 => @0.Price * @0.Qty) SUM > 100\");","handlingStrategy":"try-catch","validationCode":"// Validate the expression by attempting a dry-run translation at test time\ntry\n{\n    var test = mapper.GetExpression<MyEntity, bool>(x => x.ComplexPredicate);\n}\ncatch (NotSupportedException)\n{\n    // This LINQ construct cannot be translated -- plan to use BsonExpression instead\n}","typeGuard":null,"tryCatchPattern":"try\n{\n    var results = col.Find(predicate);\n}\ncatch (NotSupportedException ex) when (ex.Message.Contains(\"Invalid BsonExpression when converted\"))\n{\n    logger.LogWarning(\"LINQ translation failed: {Expr}\", ex.Message);\n    results = col.Find(rawBsonExpression);\n}","preventionTips":["Keep LINQ query expressions simple and within the known-supported surface.","Write integration tests that exercise each query predicate to catch translation failures early.","Have a raw BsonExpression fallback ready for complex predicates.","Check the inner exception for the exact BsonExpression parse error to pinpoint the fragment."],"tags":["linq","bson-expression","translation"],"backgroundTag":null,"analyzedSha":"f906a5f850678719e39a39a006cb66dcae563cfa","analyzedAt":"2026-08-13T21:56:30.148Z","schemaVersion":2},"datasetVersion":"2026-08-14T05:17:29.042Z"}