{"record":{"id":"51a720842464ae3f","repo":"dotnet/efcore","slug":"the-linq-expression-expression-could-not-be-tr-51a720","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/CosmosQueryTranslationPostprocessor.cs","lineNumber":173,"sourceCode":"            {\n                return;\n            }\n\n            foreach (var primaryKeyProperty in primaryKeyProperties)\n            {\n                if (string.Equals(primaryKeyProperty.GetJsonPropertyName(), propertyName, StringComparison.Ordinal))\n                {\n                    ProjectedKeyProperties.Add(primaryKeyProperty);\n                    return;\n                }\n            }\n        }\n\n        private int GetProjectionIndex(ProjectionBindingExpression projectionBindingExpression)\n            => projectionBindingExpression.ProjectionMember is not null\n                ? selectExpression.GetMappedProjection(projectionBindingExpression.ProjectionMember).GetConstantValue<int>()\n                : projectionBindingExpression.Index\n                ?? throw new InvalidOperationException(CoreStrings.TranslationFailed(projectionBindingExpression.Print()));\n\n        private bool IsRootEntityType(IEntityType entityType)\n            => entityType == rootEntityType\n                || entityType.GetRootType() == rootEntityType.GetRootType();\n    }\n\n    private sealed class ProjectionBindingIndexRemappingExpressionVisitor(\n        SelectExpression selectExpression,\n        IReadOnlyList<int> oldIndexToNewIndex)\n        : ExpressionVisitor\n    {\n        protected override Expression VisitExtension(Expression node)\n            => node switch\n            {\n                ShapedQueryExpression => node,\n                ProjectionBindingExpression\n                {\n                    QueryExpression: var queryExpression,","sourceCodeStart":155,"sourceCodeEnd":191,"githubUrl":"https://github.com/dotnet/efcore/blob/3a2006ef569de08368d59db5e1468aa8f407e4f8/src/EFCore.Cosmos/Query/Internal/CosmosQueryTranslationPostprocessor.cs#L155-L191","documentation":"During NoTrackingWithIdentityResolution postprocessing the visitor resolves each ProjectionBindingExpression to a projection index. If a binding has neither a ProjectionMember nor an Index it cannot be remapped and EF throws the shared CoreStrings.TranslationFailed, telling you the expression printed form cannot be translated by the Cosmos provider.","triggerScenarios":"An expression tree in the projection contains a node the Cosmos query pipeline cannot map to a SQL projection (e.g. a client-side method call, complex grouping, or unsupported aggregate) inside a NoTrackingWithIdentityResolution query that touches owned entities.","commonSituations":"Porting a relational query that uses client-evaluable methods in the selector, mixing owned-entity projection with custom compute, or hitting a provider gap on a newer LINQ operator.","solutions":["Rewrite the projection to use only translatable operators (remove client-side method calls, computed properties, unsupported aggregates).","Move untranslatable computation after .AsEnumerable()/.ToListAsync() so it runs client-side explicitly.","Simplify the projection to confirm which element fails to translate, then re-introduce pieces one at a time."],"exampleFix":"// before\nvar q = db.Users.AsNoTrackingWithIdentityResolution()\n    .Select(u => new { u.Id, Label = FormatLabel(u.Name) });\n// after\nvar raw = await db.Users.AsNoTrackingWithIdentityResolution()\n    .Select(u => new { u.Id, u.Name }).ToListAsync();\nvar result = raw.Select(r => new { r.Id, Label = FormatLabel(r.Name) });","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"try\n{\n    var result = await query.ToListAsync(cancellationToken);\n}\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"could not be translated\"))\n{\n    logger.LogWarning(ex, \"Cosmos translation failed; falling back to client eval\");\n    var raw = await query.AsNoTracking().Select(x => x).ToListAsync(cancellationToken);\n    // project client-side\n}","preventionTips":["Reduce the projection to a known-translatable subset, then re-introduce pieces.","Push client-only computation after ToListAsync.","Keep an integration test per projection so regressions surface early."],"tags":["cosmos","query-translation","no-tracking","projection"],"backgroundTag":null,"analyzedSha":"3a2006ef569de08368d59db5e1468aa8f407e4f8","analyzedAt":"2026-08-11T23:42:04.146Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}