{"record":{"id":"19111d9c266cd54a","repo":"dotnet/efcore","slug":"withpartitionkey-can-only-be-called-once-in-a-qu","errorCode":null,"errorMessage":"'WithPartitionKey' can only be called once in a query. See https://aka.ms/efdocs-cosmos-partition-keys for more information.","messagePattern":"'WithPartitionKey' can only be called once in a query\\. 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":170,"sourceCode":"                        translatedResponseContinuationTokenLimitInKb,\n                        typeof(CosmosPage<>).MakeGenericType(shapedQuery.ShaperExpression.Type)))\n                .UpdateResultCardinality(ResultCardinality.Single);\n        }\n\n        return base.Translate(expression);\n    }\n\n    /// <inheritdoc />\n    protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)\n    {\n        var method = methodCallExpression.Method;\n\n        if (methodCallExpression.Method.DeclaringType == typeof(CosmosQueryableExtensions)\n            && methodCallExpression.Method.Name == nameof(CosmosQueryableExtensions.WithPartitionKey))\n        {\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);","sourceCodeStart":152,"sourceCodeEnd":188,"githubUrl":"https://github.com/dotnet/efcore/blob/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.Cosmos/Query/Internal/CosmosQueryableMethodTranslatingExpressionVisitor.cs#L152-L188","documentation":"Thrown when WithPartitionKey is invoked more than once in the same Cosmos query. The provider records partition key values into a single per-query list on the compilation context and disallows a second call, because combining multiple partition-key filters is not meaningful for a single Cosmos query and would produce ambiguous semantics.","triggerScenarios":"Chaining two WithPartitionKey calls on the same queryable, e.g. context.Blogs.WithPartitionKey(\"A\").WithPartitionKey(\"B\"). Also via composing queryables where each already applies a partition key.","commonSituations":"Helper methods that each add a partition key, accidentally composed. Migrating from a multi-key relational filter pattern to Cosmos partition keys.","solutions":["Call WithPartitionKey exactly once per query, combining the relevant partition key values into a single call if multiple are supported.","Refactor shared query-building helpers so partition key is applied at the outermost composition point only.","If you need to switch partition keys, build a fresh queryable from the DbSet."],"exampleFix":"// before\nvar q = context.Blogs.WithPartitionKey(\"tenantA\").WithPartitionKey(\"region1\");\n// after\nvar q = context.Blogs.WithPartitionKey(\"tenantA\", \"region1\");","handlingStrategy":"validation","validationCode":"// Centralize partition key application and guard double-call\nif (partitionKeyApplied) throw new InvalidOperationException(\"Partition key already set\");\npartitionKeyApplied = true;\nvar q = dbSet.WithPartitionKey(tenantId);","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Apply WithPartitionKey once, at the outermost query-composition point.","Track whether a query builder already applied a partition key to avoid chaining.","Document the single-call contract in helper methods that build Cosmos queries."],"tags":["cosmos","partition-key","withpartitionkey","query"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}