{"record":{"id":"a2c39fdc4119dec6","repo":"dotnet/efcore","slug":"the-linq-expression-expression-could-not-be-tr-a2c39f","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.InMemory/Query/Internal/InMemoryProjectionBindingExpressionVisitor.cs","lineNumber":117,"sourceCode":"            {\n                switch (expression)\n                {\n                    case ConstantExpression:\n                        return expression;\n\n                    case ProjectionBindingExpression projectionBindingExpression:\n                        var mappedProjection = _queryExpression.GetProjection(projectionBindingExpression);\n                        if (mappedProjection is EntityProjectionExpression entityProjection)\n                        {\n                            return AddClientProjection(entityProjection, typeof(ValueBuffer));\n                        }\n\n                        if (mappedProjection is not InMemoryQueryExpression)\n                        {\n                            return AddClientProjection(mappedProjection, expression.Type.MakeNullable());\n                        }\n\n                        throw new InvalidOperationException(CoreStrings.TranslationFailed(projectionBindingExpression.Print()));\n\n                    case MaterializeCollectionNavigationExpression materializeCollectionNavigationExpression:\n                    {\n                        var subquery = _queryableMethodTranslatingExpressionVisitor.TranslateSubquery(\n                            materializeCollectionNavigationExpression.Subquery)!;\n                        _clientProjections!.Add(subquery.QueryExpression);\n                        return new CollectionResultShaperExpression(\n                            new ProjectionBindingExpression(\n                                _queryExpression, _clientProjections.Count - 1, typeof(IEnumerable<ValueBuffer>)),\n                            subquery.ShaperExpression,\n                            materializeCollectionNavigationExpression.Navigation,\n                            materializeCollectionNavigationExpression.Navigation.ClrType.GetSequenceType());\n                    }\n\n                    case MethodCallExpression methodCallExpression:\n                        if (methodCallExpression.Method.IsGenericMethod\n                            && methodCallExpression.Method.DeclaringType == typeof(Enumerable)\n                            && methodCallExpression.Method.Name == nameof(Enumerable.ToList)","sourceCodeStart":99,"sourceCodeEnd":135,"githubUrl":"https://github.com/dotnet/efcore/blob/3a2006ef569de08368d59db5e1468aa8f407e4f8/src/EFCore.InMemory/Query/Internal/InMemoryProjectionBindingExpressionVisitor.cs#L99-L135","documentation":"The InMemoryProjectionBindingExpressionVisitor maps each ProjectionBindingExpression to a server-side projection slot. When the mapped projection is neither an EntityProjectionExpression nor an InMemoryQueryExpression, the visitor cannot produce a shaper for it and throws TranslationFailed. This indicates a projection element that has no server-side representation in the InMemory provider.","triggerScenarios":"A LINQ Select whose projection contains an expression the InMemory provider cannot translate — e.g. calling a custom method, using a property that is not mapped, or embedding a non-translatable sub-expression in the projected shape. The throw happens at query-compilation time when the projection binding visitor walks the Select tree.","commonSituations":"Calling a CLR method inside Select that has no EF translation (e.g. .Select(x => MyHelper(x.Name))), projecting a computed expression involving unsupported constructs, or upgrading EF Core and hitting a previously-tolerated client-eval path that is now strict.","solutions":["Identify the expression fragment named in the error message and rewrite the Select to use only translatable constructs (mapped properties, arithmetic, supported methods).","Insert AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync() before the Select to force that projection to run client-side.","If the projection wraps a collection navigation, ensure it is shaped as a subquery rather than a raw method call.","Simplify the Select to the minimal shape and add complexity incrementally to isolate the un-translatable fragment."],"exampleFix":"// before — Reverse has no server translation in InMemory\nvar result = ctx.Blogs\n    .Select(b => new { b.Title, Tags = b.Tags.Reverse().ToList() });\n\n// after — materialize first, then project client-side\nvar result = ctx.Blogs\n    .AsEnumerable()\n    .Select(b => new { b.Title, Tags = b.Tags.Reverse().ToList() });","handlingStrategy":"try-catch","validationCode":"// There is no pre-flight API to detect un-translatable projections.\n// Strategy: isolate complex projections and test them; fall back to client eval.\n// Use a try/catch around query execution and retry with AsEnumerable if translation fails.\nIQueryable<T> SafeQuery<T>(IQueryable<T> q) => q; // placeholder — real guard is structural review","typeGuard":null,"tryCatchPattern":"try\n{\n    return await query.ToListAsync(cancellationToken);\n}\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"could not be translated\"))\n{\n    // Fall back: materialize server-side, then apply the problematic projection client-side\n    logger.LogWarning(\"Server translation failed; switching to client evaluation.\");\n    var serverData = baseQuery.AsEnumerable();\n    return clientProjection(serverData).ToList();\n}","preventionTips":["Keep Select projections simple — only mapped properties and supported methods.","If a projection needs a CLR method, insert AsEnumerable() before the Select.","Write integration tests for each query to catch translation failures early.","Avoid mixing custom helper method calls into server-side LINQ expressions."],"tags":["efcore","inmemory","query-translation","projection","client-eval"],"backgroundTag":null,"analyzedSha":"3a2006ef569de08368d59db5e1468aa8f407e4f8","analyzedAt":"2026-08-11T23:42:04.146Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}