{"record":{"id":"49c9f5802efb0576","repo":"litedb-org/LiteDB","slug":"expression-expr-can-t-return-null-value","errorCode":null,"errorMessage":"Expression {expr} can't return null value","messagePattern":"Expression (.+?) can't return null value","errorType":"exception","errorClass":"NotSupportedException","httpStatus":null,"severity":"error","filePath":"LiteDB/Client/Mapper/Linq/LinqExpressionVisitor.cs","lineNumber":731,"sourceCode":"            object value = null;\n\n            if (expr.NodeType == ExpressionType.Constant)\n            {\n                var constant = (ConstantExpression)expr;\n\n                value = constant.Value;\n            }\n            else\n            {\n                var func = Expression.Lambda(expr).Compile();\n\n                value = func.DynamicInvoke();\n            }\n\n            // do some type validation to be ease to debug\n            if (validTypes.Length > 0 && value == null)\n            {\n                throw new NotSupportedException($\"Expression {expr} can't return null value\");\n            }\n\n            if (validTypes.Length > 0 && validTypes.Any(x => x == value.GetType()) == false)\n            {\n                throw new NotSupportedException($\"Expression {expr} must return on of this types: {string.Join(\", \", validTypes.Select(x => $\"`{x.Name}`\"))}\");\n            }\n\n            return value;\n        }\n\n        /// <summary>\n        /// Tries to visit `new BsonRefId&lt;T&gt;(id)` within a member init expression.\n        /// This is only resolved for properties marked as DbRef.\n        /// </summary>\n        private bool TryVisitDbRefIdExpression(Expression node, MemberMapper memberMapper, bool isInList = false)\n        {\n            if (!memberMapper.IsDbRef)\n            {","sourceCodeStart":713,"sourceCodeEnd":749,"githubUrl":"https://github.com/litedb-org/LiteDB/blob/f906a5f850678719e39a39a006cb66dcae563cfa/LiteDB/Client/Mapper/Linq/LinqExpressionVisitor.cs#L713-L749","documentation":"Thrown by the private Evaluate helper when validTypes are specified (one or more expected types passed) and the expression evaluates to null. Evaluate is used to compile-and-invoke sub-expressions that must produce a concrete value (e.g., array index values, method arguments). A null result with type constraints is rejected because the downstream BsonExpression cannot represent a typed null for those positions.","triggerScenarios":"An evaluated sub-expression returns null where Evaluate was called with validTypes. For example, a closure variable used as an array index or method argument is null: x => x.Items[idx] where idx is a null variable, or Evaluate(expr, typeof(int)) where expr evaluates to null.","commonSituations":"Passing a null closure variable into a query expression that gets evaluated (index access, method arguments). A nullable variable that was never assigned being captured in the expression tree. Database-first scenarios where caller code didn't null-check a parameter before building the query.","solutions":["Null-check the variable before building the LINQ expression and throw or skip the query.","Provide a non-null default value before the variable is captured in the expression.","Ensure closure variables used as evaluated arguments (indices, method params) are always initialized."],"exampleFix":"// before\nstring key = null;\nvar results = col.Find(x => x.Data[key] != null);\n// key is null -> Evaluate throws\n\n// after\nif (key == null) throw new ArgumentNullException(nameof(key));\nvar results = col.Find(x => x.Data[key] != null);","handlingStrategy":"validation","validationCode":"// Null-check closure variables before building the query expression\nstring key = GetKey();\nif (key == null) throw new ArgumentNullException(nameof(key));\ncol.Find(x => x.Data[key] != null);","typeGuard":"// Guard against null values in evaluated expression arguments\nstatic void EnsureNotNull<T>(T value, string name) where T : class\n{\n    if (value == null) throw new ArgumentNullException(name);\n}","tryCatchPattern":"try\n{\n    var results = col.Find(x => x.Data[key] != null);\n}\ncatch (NotSupportedException ex) when (ex.Message.Contains(\"can't return null value\"))\n{\n    throw new ArgumentNullException(nameof(key), \"Query argument cannot be null.\", ex);\n}","preventionTips":["Null-check all closure variables before capturing them in query expressions.","Provide non-null defaults for optional query parameters.","Use nullable reference type annotations to catch null variables at compile time.","Validate evaluated arguments (indices, method params) before building the expression."],"tags":["linq","evaluation","null"],"backgroundTag":null,"analyzedSha":"f906a5f850678719e39a39a006cb66dcae563cfa","analyzedAt":"2026-08-13T21:56:30.148Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}