dotnet/efcore · error · InvalidOperationException

The LINQ expression '{expression}' could not be translated.

Error message

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.

What it means

A generic translation-failure thrown inside the shaper processing visitor when resolving a ProjectionBindingExpression that has neither a ProjectionMember nor an Index. This means the query's projection could not be mapped to a concrete server-side projection slot, so the compiled shaper cannot read the value.

Source

Thrown at src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs:1478

                if (_entityTypeMaterializerExpressionsMapping.TryGetValue(entityType, out var materializerExpressions))
                {
                    return materializerExpressions;
                }
            }
            while ((entityType = entityType.BaseType!) != null);

            throw new UnreachableException();
        }

        private ProjectionExpression GetProjection(ProjectionBindingExpression projectionBindingExpression)
            => ((SelectExpression)projectionBindingExpression.QueryExpression).Projection[GetProjectionIndex(projectionBindingExpression)];

        private int GetProjectionIndex(ProjectionBindingExpression projectionBindingExpression)
            => projectionBindingExpression.ProjectionMember != null
                ? ((SelectExpression)projectionBindingExpression.QueryExpression)
                .GetMappedProjection(projectionBindingExpression.ProjectionMember).GetConstantValue<int>()
                : (projectionBindingExpression.Index
                    ?? throw new InvalidOperationException(CoreStrings.TranslationFailed(projectionBindingExpression.Print())));

        private NewExpression NewJsonReaderManager()
            => New(
                JsonReaderManagerConstructor, _jsonReaderDataParameter,
                MakeMemberAccess(QueryCompilationContext.QueryContextParameter, QueryContextQueryLoggerProperty));

        private static UnaryExpression ThrowInvalidToken(Expression tokenType, Type? type = null)
            => Throw(Call(CreateJsonReaderInvalidTokenTypeMethodInfo, tokenType), type ?? typeof(void));

        private ParameterExpression[] GetParametersForLambda(ITypeBase structuralType)
            => structuralType.TryGetOrdinalKey(out _)
                ? [QueryCompilationContext.QueryContextParameter, _jsonReaderDataParameter, _ownerKeySnapshotParameter, _ordinalParameter]
                : [QueryCompilationContext.QueryContextParameter, _jsonReaderDataParameter, _ownerKeySnapshotParameter];

        private bool IsTracking(ITypeBase structuralType, [NotNullWhen(true)] out IEntityType? entityType)
        {
            entityType = structuralType as IEntityType;
            return _queryStateManager && entityType != null && entityType.FindPrimaryKey() != null;

View on GitHub (pinned to dbf9771522)

Solutions

  1. Simplify the projection to direct property bindings supported by Cosmos.
  2. Move untranslatable projection logic to the client via AsAsyncEnumerable().
  3. Project an anonymous type of raw properties first, then map to the DTO on the client.
  4. Check EF Core Cosmos release notes for supported projection operators.

Example fix

// before
var result = await context.Blogs
    .Select(b => new BlogDto(b.Title, ComputeRank(b.Score)))
    .ToListAsync();
// after
var result = await context.Blogs
    .Select(b => new { b.Title, b.Score })
    .AsAsyncEnumerable()
    .Select(x => new BlogDto(x.Title, ComputeRank(x.Score)))
    .ToListAsync();
Defensive patterns

Strategy: fallback

Try / catch

try
{
    return await query.ToListAsync();
}
catch (InvalidOperationException ex) when (ex.Message.Contains("could not be translated"))
{
    return await query.Select(x => x /* properties only */).AsAsyncEnumerable().ToListAsync();
}

Prevention

When it happens

Trigger: A LINQ projection that the Cosmos shaper compiler cannot bind to the SelectExpression's projection list, often due to unsupported projection shapes, complex DTO constructors, or client-side methods inside Select.

Common situations: Projecting into DTOs with non-translatable constructors or helper calls, grouping, or using operators the Cosmos provider does not support inside the projection.

Related errors


AI-assisted analysis of dotnet/efcore@dbf9771522 (2026-08-06). Data as JSON: /api/errors/d7dda301a6861292. Report an issue: GitHub.