{"record":{"id":"00db0f69609b8ecb","repo":"dotnet/efcore","slug":"unable-to-generate-a-valid-id-value-to-execute-a","errorCode":null,"errorMessage":"Unable to generate a valid 'id' value to execute a 'ReadItem' query. This usually happens when the value provided for one of the properties is 'null' or an empty string. Provide a value that's not 'null' or an empty string.","messagePattern":"Unable to generate a valid 'id' value to execute a 'ReadItem' query\\. This usually happens when the value provided for one of the properties is 'null' or an empty string\\. Provide a value that's not 'null' or an empty string\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ReadItemQueryingEnumerable.cs","lineNumber":94,"sourceCode":"            Check.DebugAssert(\n                jsonIdDefinition != null,\n                \"Should not be using this enumerable if not using ReadItem, which needs an id definition.\");\n\n            var values = new List<object>(jsonIdDefinition.Properties.Count);\n            foreach (var property in jsonIdDefinition.Properties)\n            {\n                var value = _readItemInfo.PropertyValues[property] switch\n                {\n                    SqlParameterExpression { Name: var parameterName } => _cosmosQueryContext.Parameters[parameterName],\n                    SqlConstantExpression { Value: var constantValue } => constantValue,\n                    _ => throw new UnreachableException()\n                };\n\n                values.Add(value);\n            }\n\n            resourceId = jsonIdDefinition.GenerateIdString(values);\n            return string.IsNullOrEmpty(resourceId) ? throw new InvalidOperationException(CosmosStrings.InvalidResourceId) : true;\n        }\n\n        private sealed class AsyncEnumerator : IAsyncEnumerator<T>\n        {\n            private readonly CosmosQueryContext _cosmosQueryContext;\n            private readonly string _cosmosContainer;\n            private readonly PartitionKey _cosmosPartitionKey;\n            private readonly Shaper<T> _shaper;\n            private readonly Type _contextType;\n            private readonly IDiagnosticsLogger<DbLoggerCategory.Query> _queryLogger;\n            private readonly bool _standAloneStateManager;\n            private readonly IConcurrencyDetector _concurrencyDetector;\n            private readonly IExceptionDetector _exceptionDetector;\n            private readonly ReadItemQueryingEnumerable<T> _readItemEnumerable;\n            private readonly CancellationToken _cancellationToken;\n\n            private ReadOnlyMemory<byte>? _response;\n            private bool _hasExecuted;","sourceCodeStart":76,"sourceCodeEnd":112,"githubUrl":"https://github.com/dotnet/efcore/blob/3a2006ef569de08368d59db5e1468aa8f407e4f8/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ReadItemQueryingEnumerable.cs#L76-L112","documentation":"When a query is optimized to a Cosmos ReadItem, EF builds the 'id' resource string from configured key property values via jsonIdDefinition.GenerateIdString. If the resulting id is null or empty (a constituent value was null or empty string) TryGetResourceId throws InvalidOperationException with InvalidResourceId.","triggerScenarios":"Querying for an entity by a key where one of the key property values is null or an empty string, so the generated document id is not a legal Cosmos resource id.","commonSituations":"Default/null key values on a partition key component, an empty string for the id property due to bad seed data, or a key property whose value comes from an unset request parameter.","solutions":["Ensure all key property values contributing to the id are non-null and non-empty before issuing the lookup.","Validate key inputs at the API boundary with a guard clause.","If a key component legitimately may be empty, reconsider whether ReadItem optimization is appropriate (filter the property instead)."],"exampleFix":"// before\nvar u = await db.Users.FirstOrDefaultAsync(x => x.Id == maybeEmptyId);\n// after\nif (string.IsNullOrEmpty(maybeEmptyId)) throw new ArgumentException(\"Id required\", nameof(maybeEmptyId));\nvar u = await db.Users.FirstOrDefaultAsync(x => x.Id == maybeEmptyId);","handlingStrategy":"validation","validationCode":"static async Task<T?> GetByIdAsync<T>(DbSet<T> set, string id, CancellationToken ct)\n    where T : class\n{\n    if (string.IsNullOrEmpty(id)) throw new ArgumentException(\"id required\", nameof(id));\n    return await set.FirstOrDefaultAsync(e => EF.Property<string>(e, \"Id\") == id, ct).ConfigureAwait(false);\n}","typeGuard":"static bool IsValidResourceId(string? id) => !string.IsNullOrWhiteSpace(id);","tryCatchPattern":null,"preventionTips":["Validate key values at the API boundary before querying.","Use nullable reference types so null key values surface at compile time.","Add a unit test that asserts lookup-by-empty-key throws your guard, not EF."],"tags":["cosmos","readitem","keys","validation"],"backgroundTag":null,"analyzedSha":"3a2006ef569de08368d59db5e1468aa8f407e4f8","analyzedAt":"2026-08-11T23:42:04.146Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}