{"record":{"id":"464a038635598622","repo":"dotnet/efcore","slug":"withpartitionkey-only-accepts-simple-constant-or","errorCode":null,"errorMessage":"'WithPartitionKey' only accepts simple constant or parameter arguments. See https://aka.ms/efdocs-cosmos-partition-keys for more information.","messagePattern":"'WithPartitionKey' only accepts simple constant or parameter arguments\\. See https://aka\\.ms/efdocs-cosmos-partition-keys for more information\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Cosmos/Query/Internal/CosmosQueryableMethodTranslatingExpressionVisitor.cs","lineNumber":185,"sourceCode":"        {\n            if (_queryCompilationContext.PartitionKeyPropertyValues.Count > 0)\n            {\n                throw new InvalidOperationException(CosmosStrings.WithPartitionKeyAlreadyCalled);\n            }\n\n            if (methodCallExpression.Arguments[0] is not EntityQueryRootExpression)\n            {\n                throw new InvalidOperationException(CosmosStrings.WithPartitionKeyBadNode);\n            }\n\n            var innerQueryable = Visit(methodCallExpression.Arguments[0]);\n\n            for (var i = 1; i < methodCallExpression.Arguments.Count; i++)\n            {\n                var value = _sqlTranslator.Translate(methodCallExpression.Arguments[i], applyDefaultTypeMapping: false);\n                if (value is not SqlConstantExpression and not SqlParameterExpression)\n                {\n                    throw new InvalidOperationException(CosmosStrings.WithPartitionKeyNotConstantOrParameter);\n                }\n\n                _queryCompilationContext.PartitionKeyPropertyValues.Add(value);\n            }\n\n            return innerQueryable;\n        }\n\n        if (method.DeclaringType == typeof(Queryable) && method.IsGenericMethod)\n        {\n            switch (methodCallExpression.Method.Name)\n            {\n                // The following is a bad hack to account for https://github.com/dotnet/efcore/issues/32957#issuecomment-2165864086.\n                // Basically for the query form Where(b => b.Posts.GetElementAt(0).Id == 1), nav expansion moves the property access\n                // forward, generating Where(b => b.Posts.Select(p => p.Id).GetElementAt(0)); unfortunately that means that GetElementAt()\n                // over a bare array in Cosmos doesn't get translated to a simple indexer as it should (b[\"Posts\"][0].Id), since the\n                // reordering messes things up.\n                case nameof(Queryable.ElementAt) or nameof(Queryable.ElementAtOrDefault)","sourceCodeStart":167,"sourceCodeEnd":203,"githubUrl":"https://github.com/dotnet/efcore/blob/3a2006ef569de08368d59db5e1468aa8f407e4f8/src/EFCore.Cosmos/Query/Internal/CosmosQueryableMethodTranslatingExpressionVisitor.cs#L167-L203","documentation":"After translating each WithPartitionKey argument with applyDefaultTypeMapping:false, the visitor requires the result to be a SqlConstantExpression or SqlParameterExpression. Any other shape (a column reference, a computed expression, a client value that cannot be mapped) triggers InvalidOperationException.","triggerScenarios":"Passing a non-constant/non-parameter value to WithPartitionKey — e.g. a property of another entity, the result of a method call, or an expression that requires translation rather than binding.","commonSituations":"Computing the partition key at runtime from another query result and passing it in, or capturing a non-simple value (struct without type mapping, dynamic) as the partition key.","solutions":["Pass a simple constant or a parameter captured in a local variable (string, int, etc.) to WithPartitionKey.","Resolve any computed partition key to a concrete value before calling WithPartitionKey.","Ensure the partition key CLR type has a Cosmos type mapping registered."],"exampleFix":"// before\nvar q = db.Users.WithPartitionKey(otherUser.TenantId);\n// after\nvar tenantId = otherUser.TenantId;\nvar q = db.Users.WithPartitionKey(tenantId);","handlingStrategy":"validation","validationCode":"static IQueryable<T> SafePartition<T>(IQueryable<T> q, object key)\n    where T : class\n{\n    if (key is null) throw new ArgumentNullException(nameof(key));\n    if (key is string s && s.Length == 0) throw new ArgumentException(\"empty partition key\", nameof(key));\n    if (!key.GetType().IsPrimitive && key is not string and not Guid and not DateTime and not DateTimeOffset)\n        throw new ArgumentException(\"partition key must be a simple constant or parameter\", nameof(key));\n    return q.WithPartitionKey(key);\n}","typeGuard":"static bool IsSimplePartitionValue(object v)\n    => v is string or Guid or DateTime or DateTimeOffset || v?.GetType().IsPrimitive == true;","tryCatchPattern":null,"preventionTips":["Resolve partition keys to concrete locals before calling WithPartitionKey.","Avoid passing property accessors or method results as partition key arguments.","Add an analyzer rule that flags non-constant/parameter arguments to WithPartitionKey."],"tags":["cosmos","partition-key","query-translation","parameters"],"backgroundTag":null,"analyzedSha":"3a2006ef569de08368d59db5e1468aa8f407e4f8","analyzedAt":"2026-08-11T23:42:04.146Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}