{"record":{"id":"7ab816353f46bc3e","repo":"dotnet/efcore","slug":"private-static-field-access","errorCode":null,"errorMessage":"Private static field access","messagePattern":"Private static field access","errorType":"exception","errorClass":"NotImplementedException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Design/Query/Internal/LinqToCSharpSyntaxTranslator.cs","lineNumber":1674,"sourceCode":"\n                Result = MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, expression, IdentifierName(member.Member.Name));\n                break;\n        }\n\n        return member;\n    }\n\n    /// <summary>\n    ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to\n    ///     the same compatibility standards as public APIs. It may be changed or removed without notice in\n    ///     any release. You should only use it directly in your code with extreme caution and knowing that\n    ///     doing so can result in application failures when updating to a new Entity Framework Core release.\n    /// </summary>\n    protected virtual void TranslateNonPublicMemberAccess(MemberExpression memberExpression)\n    {\n        if (memberExpression.Expression is null)\n        {\n            throw new NotImplementedException(\"Private static field access\");\n        }\n\n        // Get an unsafe accessor for this field/property (this internally caches and adds it to the output list of unsafe accessors)\n\n        // [UnsafeAccessor(UnsafeAccessorKind.Field, Name = \"<Name>k__BackingField\")]\n        // static extern ref int UnsafeAccessor_Foo_Name(Foo f);\n        var unsafeAccessorDeclaration = GetUnsafeAccessorDeclaration(\n            memberExpression.Member is PropertyInfo propertyInfo\n                ? propertyInfo.GetMethod ?? throw new UnreachableException(\"Attempting to read from property without getter\")\n                : memberExpression.Member,\n            forWrite: false);\n\n        // The unsafe accessor declaration has been created; invoke it.\n        Result =\n            _g.InvocationExpression(\n                _g.IdentifierName(unsafeAccessorDeclaration.Identifier.Text),\n                Translate<ExpressionSyntax>(memberExpression.Expression));\n    }","sourceCodeStart":1656,"sourceCodeEnd":1692,"githubUrl":"https://github.com/dotnet/efcore/blob/3a2006ef569de08368d59db5e1468aa8f407e4f8/src/EFCore.Design/Query/Internal/LinqToCSharpSyntaxTranslator.cs#L1656-L1692","documentation":"Thrown by LinqToCSharpSyntaxTranslator.TranslateNonPublicMemberAccess when a MemberExpression for a non-public member has a null Expression — i.e. the member is being accessed statically (memberExpression.Expression is null). The [UnsafeAccessor]-based pattern only handles instance access; private static field/property read is not implemented.","triggerScenarios":"An expression tree contains a MemberExpression referencing a private/internal static field or a private static property's getter with no object instance, and that member reaches the non-public member access path of the translator.","commonSituations":"Manually-constructed expression trees that read private static state (singletons, caches) for compiled-query source generation; provider extensions that wrap internal static fields; reflective helpers that surface static private members as MemberExpression.","solutions":["Avoid reading private static fields/properties through expression trees destined for this translator; expose the value via a public static accessor and reference that instead.","If the value is constant, compute it out-of-band and inject it as a ConstantExpression.","Restructure so the access is on an instance rather than static (pass the holder object into the lambda)."],"exampleFix":"// before — reads a private static field via reflection-built MemberExpression\nvar field = typeof(Config).GetField(\"s_value\",\n    BindingFlags.NonPublic | BindingFlags.Static)!;\nvar access = Expression.Field(null, field); // null target => static\n\n// after — expose a public static accessor and reference it\npublic static int Value => s_value;\nvar access = Expression.Property(null, nameof(Config.Value));","handlingStrategy":"validation","validationCode":"// Reject MemberExpressions that target non-public static members.\nusing System.Linq.Expressions;\nusing System.Reflection;\n\nbool TargetsPrivateStaticMember(Expression e)\n{\n    bool bad = false;\n    new MemberChecker(m =>\n    {\n        if (m.Expression is null && m.Member is not null)\n        {\n            var accessibility = m.Member switch\n            {\n                FieldInfo f => f.Attributes,\n                PropertyInfo p => p.GetMethod?.Attributes ?? MethodAttributes.Private,\n                _ => MethodAttributes.Private,\n            };\n            if (!accessibility.HasFlag(MethodAttributes.Public)) bad = true;\n        }\n    }).Visit(e);\n    return bad;\n}\n\nclass MemberChecker(Action<MemberExpression> onMember) : ExpressionVisitor\n{\n    protected override Expression VisitMember(MemberExpression m) { onMember(m); return base.VisitMember(m); }\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Expose static state through public accessors; do not read private statics via expression trees.","Replace reads of private static fields with constants when the value does not change.","Pre-scan the tree for static-typed MemberExpressions whose members are non-public."],"tags":["ef-core","expression-trees","reflection","unsafe-accessor","static","code-generation"],"backgroundTag":null,"analyzedSha":"3a2006ef569de08368d59db5e1468aa8f407e4f8","analyzedAt":"2026-08-11T23:42:04.146Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}