{"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/3a2006ef569de08368d59db5e1468aa8f407e4f8/src/EFCore.Cosmos/Query/Internal/CosmosQueryableMethodTranslatingExpressionVisitor.cs#L152-L188","documentation":"CosmosQueryableExtensions.WithPartitionKey records partition key values on the QueryCompilationContext. The visitor checks PartitionKeyPropertyValues.Count before processing and, if it is already populated, throws InvalidOperationException — partition key can only be fixed once per query.","triggerScenarios":"Calling .WithPartitionKey(...) twice on the same IQueryable, or composing two queryables each of which already carries a WithPartitionKey call.","commonSituations":"Reusable query filters that bake in WithPartitionKey being combined with an ad-hoc per-call WithPartitionKey, or multi-tenant helpers that set the partition key and the caller also sets it.","solutions":["Call WithPartitionKey exactly once per query lifecycle.","Centralize partition key injection in one helper and guard against double-application.","Build the query from a single root, applying WithPartitionKey at the start, before any further composition."],"exampleFix":"// before\nvar q = db.Users.WithPartitionKey(\"tenantA\").Where(u => u.Active).WithPartitionKey(\"tenantA\");\n// after\nvar q = db.Users.WithPartitionKey(\"tenantA\").Where(u => u.Active);","handlingStrategy":"validation","validationCode":"static IQueryable<T> PartitionOnce<T>(IQueryable<T> q, params object[] keys)\n    where T : class\n{\n    if (q is IQueryable<T> already && already.Provider.GetType().Name.Contains(\"Cosmos\"))\n    {\n        // call WithPartitionKey only on a fresh DbSet root; track via a marker extension if needed\n    }\n    return q.WithPartitionKey(keys);\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Centralize WithPartitionKey in one repository method.","Never combine two IQueryables that each applied WithPartitionKey.","Document the 'once per query' rule in the helper's XML doc."],"tags":["cosmos","partition-key","query-translation"],"backgroundTag":null,"analyzedSha":"3a2006ef569de08368d59db5e1468aa8f407e4f8","analyzedAt":"2026-08-11T23:42:04.146Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}