{"record":{"id":"d7dda301a6861292","repo":"dotnet/efcore","slug":"the-linq-expression-expression-could-not-be-tr-d7dda3","errorCode":null,"errorMessage":"The LINQ expression '{expression}' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.","messagePattern":"The LINQ expression '(.+?)' could not be translated\\. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'\\. See https://go\\.microsoft\\.com/fwlink/\\?linkid=2101038 for more information\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs","lineNumber":1478,"sourceCode":"                if (_entityTypeMaterializerExpressionsMapping.TryGetValue(entityType, out var materializerExpressions))\n                {\n                    return materializerExpressions;\n                }\n            }\n            while ((entityType = entityType.BaseType!) != null);\n\n            throw new UnreachableException();\n        }\n\n        private ProjectionExpression GetProjection(ProjectionBindingExpression projectionBindingExpression)\n            => ((SelectExpression)projectionBindingExpression.QueryExpression).Projection[GetProjectionIndex(projectionBindingExpression)];\n\n        private int GetProjectionIndex(ProjectionBindingExpression projectionBindingExpression)\n            => projectionBindingExpression.ProjectionMember != null\n                ? ((SelectExpression)projectionBindingExpression.QueryExpression)\n                .GetMappedProjection(projectionBindingExpression.ProjectionMember).GetConstantValue<int>()\n                : (projectionBindingExpression.Index\n                    ?? throw new InvalidOperationException(CoreStrings.TranslationFailed(projectionBindingExpression.Print())));\n\n        private NewExpression NewJsonReaderManager()\n            => New(\n                JsonReaderManagerConstructor, _jsonReaderDataParameter,\n                MakeMemberAccess(QueryCompilationContext.QueryContextParameter, QueryContextQueryLoggerProperty));\n\n        private static UnaryExpression ThrowInvalidToken(Expression tokenType, Type? type = null)\n            => Throw(Call(CreateJsonReaderInvalidTokenTypeMethodInfo, tokenType), type ?? typeof(void));\n\n        private ParameterExpression[] GetParametersForLambda(ITypeBase structuralType)\n            => structuralType.TryGetOrdinalKey(out _)\n                ? [QueryCompilationContext.QueryContextParameter, _jsonReaderDataParameter, _ownerKeySnapshotParameter, _ordinalParameter]\n                : [QueryCompilationContext.QueryContextParameter, _jsonReaderDataParameter, _ownerKeySnapshotParameter];\n\n        private bool IsTracking(ITypeBase structuralType, [NotNullWhen(true)] out IEntityType? entityType)\n        {\n            entityType = structuralType as IEntityType;\n            return _queryStateManager && entityType != null && entityType.FindPrimaryKey() != null;","sourceCodeStart":1460,"sourceCodeEnd":1496,"githubUrl":"https://github.com/dotnet/efcore/blob/3a2006ef569de08368d59db5e1468aa8f407e4f8/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs#L1460-L1496","documentation":"Inside ShaperProcessingExpressionVisitor, GetProjectionIndex resolves a ProjectionBindingExpression to a SelectExpression projection index. If the binding has no ProjectionMember and a null Index, it cannot be remapped and the visitor throws CoreStrings.TranslationFailed with the printed expression — meaning the projection binding could not be tied to any Cosmos SQL projection.","triggerScenarios":"A query whose shaper references a projection binding that the Cosmos SelectExpression never produced — usually a binding created by a relational-only translation step or by a hand-built ExpressionTree.","commonSituations":"Mixing relational query visitors with Cosmos queries, custom IQueryTranslationPostprocessors that introduce bindings, or hitting an EF provider gap where a binding is emitted but no matching projection exists.","solutions":["Simplify the query (remove computed projections, grouping, subqueries) to isolate the binding that fails.","Avoid custom expression-tree manipulation that creates ProjectionBindingExpression without a backing projection.","Report the minimal repro to the EF Cosmos provider if it reproduces on stock LINQ."],"exampleFix":null,"handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"try { await query.ToListAsync(ct); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"could not be translated\"))\n{\n    logger.LogWarning(ex, \"Projection binding failed; simplifying query\");\n    // simplify projection and retry\n}","preventionTips":["Do not introduce ProjectionBindingExpression from custom visitors.","Keep relational vs Cosmos query visitors separate.","Add a smoke test per projection to catch binding regressions."],"tags":["cosmos","query-translation","shaper","projection"],"backgroundTag":null,"analyzedSha":"3a2006ef569de08368d59db5e1468aa8f407e4f8","analyzedAt":"2026-08-11T23:42:04.146Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}