{"record":{"id":"e9205a6561979392","repo":"dotnet/efcore","slug":"the-same-parameterexpression-instance-with-name","errorCode":null,"errorMessage":"The same ParameterExpression instance with name '{parameter}' was used as a variable declaration in a block and a nested block inside it. This is not allowed - use different ParameterExpression instances.","messagePattern":"The same ParameterExpression instance with name '(.+?)' was used as a variable declaration in a block and a nested block inside it\\. This is not allowed - use different ParameterExpression instances\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Design/Query/Internal/LinqToCSharpSyntaxTranslator.cs","lineNumber":516,"sourceCode":"        {\n            var (variables, variableNames) = (stackFrame.Variables, stackFrame.VariableNames);\n\n            var uniquifiedName = UniquifyVariableName(parameter.Name ?? \"unnamed\");\n\n            if (blockContext == ExpressionContext.Expression)\n            {\n                if (!_liftedState.Variables.TryAdd(parameter, uniquifiedName))\n                {\n                    throw new NotSupportedException(\"Parameter clash during expression lifting for: \" + parameter.Name);\n                }\n\n                _liftedState.VariableNames.Add(uniquifiedName);\n            }\n            else\n            {\n                if (!variables.TryAdd(parameter, uniquifiedName))\n                {\n                    throw new InvalidOperationException(\n                        DesignStrings.SameParameterExpressionDeclaredAsVariableInNestedBlocks(parameter.Name ?? \"<null>\"));\n                }\n\n                variableNames.Add(uniquifiedName);\n            }\n        }\n\n        var unassignedVariables = block.Variables.ToList();\n\n        var statements = new List<StatementSyntax>();\n        LabeledStatementSyntax? pendingLabeledStatement = null;\n\n        // Now visit the block's expressions\n        for (var i = 0; i < block.Expressions.Count; i++)\n        {\n            var expression = block.Expressions[i];\n            var onLastBlockLine = i == block.Expressions.Count - 1;\n            _onLastLambdaLine = parentOnLastLambdaLine && onLastBlockLine;","sourceCodeStart":498,"sourceCodeEnd":534,"githubUrl":"https://github.com/dotnet/efcore/blob/3a2006ef569de08368d59db5e1468aa8f407e4f8/src/EFCore.Design/Query/Internal/LinqToCSharpSyntaxTranslator.cs#L498-L534","documentation":"Thrown by LinqToCSharpSyntaxTranslator.VisitBlock when the same ParameterExpression instance is added as a variable to a non-lifted block scope (the local StackFrame) but it is already registered. LINQ treats ParameterExpression by reference identity; reusing one instance as a variable in both an outer and nested (non-lifted) block produces ambiguous C# because the variable's declaration scope is unclear.","triggerScenarios":"An expression tree built manually reuses a single ParameterExpression instance in the Variables collection of two nested BlockExpressions that are both rendered as statement scopes (i.e. neither is an expression-context block that gets lifted).","commonSituations":"Hand-rolled expression-tree builders that share a ParameterExpression across blocks for convenience; refactoring Expression.Variable calls into a shared field; converting imperative code that used the same symbol name into nested blocks.","solutions":["Allocate a fresh ParameterExpression for each block scope that declares the variable; do not reuse instances across sibling/nested declaration scopes.","If you must share by name, declare the variable once in the outermost block and do not re-declare it in nested blocks.","Audit tree construction with Expression.Parameter equality-by-reference in mind — equal names do not imply equal identity."],"exampleFix":"// before — same instance reused across nested block scopes\nvar v = Expression.Variable(typeof(int), \"x\");\nvar inner = Expression.Block(\n    new[] { v },\n    Expression.Assign(v, Expression.Constant(1)));\nvar outer = Expression.Block(\n    new[] { v },\n    inner,\n    Expression.Add(v, Expression.Constant(2)));\n\n// after — distinct instances per scope\nvar vOuter = Expression.Variable(typeof(int), \"x\");\nvar vInner = Expression.Variable(typeof(int), \"x\");\nvar inner = Expression.Block(\n    new[] { vInner },\n    Expression.Assign(vInner, Expression.Constant(1)));\nvar outer = Expression.Block(\n    new[] { vOuter },\n    inner,\n    Expression.Add(vOuter, Expression.Constant(2)));","handlingStrategy":"validation","validationCode":"// Verify no ParameterExpression is reused as a variable across nested blocks.\nusing System.Linq.Expressions;\n\nbool HasSharedVariableInNestedBlocks(Expression e)\n{\n    var stack = new Stack<HashSet<ParameterExpression>>();\n    bool clash = false;\n    new NestedBlockVisitor(() => stack, () =>\n    {\n        // called when a duplicate is detected\n        clash = true;\n    }).Visit(e);\n    return clash;\n}\n\n// A simplified visitor skeleton:\nclass NestedBlockVisitor : ExpressionVisitor\n{\n    private readonly Stack<HashSet<ParameterExpression>> _scope;\n    private readonly Action _onClash;\n    public NestedBlockVisitor(Func<Stack<HashSet<ParameterExpression>>> scope, Action onClash)\n    { _scope = scope(); _onClash = onClash; }\n    protected override Expression VisitBlock(BlockExpression b)\n    {\n        var current = new HashSet<ParameterExpression>();\n        foreach (var v in b.Variables)\n            if (!current.Add(v)) _onClash();\n        _scope.Push(current);\n        var r = base.VisitBlock(b);\n        _scope.Pop();\n        return r;\n    }\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Allocate a fresh ParameterExpression per declaration scope; never share an instance between sibling/nested blocks.","Remember ParameterExpression equality is by reference, not by Name.","Use a builder helper that allocates and tracks variables per scope to prevent accidental sharing."],"tags":["ef-core","expression-trees","linq-expressions","code-generation","parameter-expression","blocks"],"backgroundTag":null,"analyzedSha":"3a2006ef569de08368d59db5e1468aa8f407e4f8","analyzedAt":"2026-08-11T23:42:04.146Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}