dotnet/efcore · error · InvalidOperationException

Using 'Distinct' operation on a projection containing a subq

Error message

Using 'Distinct' operation on a projection containing a subquery is not supported.

What it means

ApplyDistinct iterates client projections and throws if any projection is itself an InMemoryQueryExpression (a subquery) (InMemoryQueryExpression.cs:513-515). The provider cannot compare subquery result sets for distinctness.

Source

Thrown at src/EFCore.InMemory/Query/Internal/InMemoryQueryExpression.cs:515

        var selectorExpressions = new List<Expression>();
        if (_clientProjections.Count == 0)
        {
            selectorExpressions.AddRange(_projectionMappingExpressions);
            if (selectorExpressions.Count == 0)
            {
                // No server correlated term in projection so add dummy 1.
                selectorExpressions.Add(Constant(1));
            }
        }
        else
        {
            for (var i = 0; i < _clientProjections.Count; i++)
            {
                var projection = _clientProjections[i];
                if (projection is InMemoryQueryExpression)
                {
                    throw new InvalidOperationException(InMemoryStrings.DistinctOnSubqueryNotSupported);
                }

                if (projection is EntityProjectionExpression entityProjectionExpression)
                {
                    _clientProjections[i] = TraverseEntityProjection(
                        selectorExpressions, entityProjectionExpression, makeNullable: false);
                }
                else
                {
                    selectorExpressions.Add(projection);
                    _clientProjections[i] = CreateReadValueExpression(
                        projection.Type, selectorExpressions.Count - 1, InferPropertyFromInner(projection));
                }
            }
        }

        var selectorLambda = Lambda(
            New(

View on GitHub (pinned to dbf9771522)

Solutions

  1. Remove the subquery from the projection before calling Distinct.
  2. Call AsEnumerable() before Distinct to deduplicate client-side.
  3. Apply Distinct to a simpler projection first, then load related data separately.

Example fix

// before
var q = db.Blogs
    .Select(b => new { b, Posts = b.Posts.ToList() })
    .Distinct();
// after
var q = db.Blogs.Distinct()
    .Select(b => new { b, Posts = b.Posts.ToList() });
Defensive patterns

Strategy: try-catch

Try / catch

try
{
    var r = query.Select(projWithSubquery).Distinct().ToList();
}
catch (InvalidOperationException ex) when (ex.Message.Contains("Distinct"))
{
    var r = query.AsEnumerable().Select(projWithSubquery).Distinct().ToList();
}

Prevention

When it happens

Trigger: Calling Distinct() on a query whose projection includes a subquery, e.g. db.Blogs.Select(b => new { b, Top = b.Posts.OrderByDescending(p => p.Id).FirstOrDefault() }).Distinct().

Common situations: Projecting correlated/related data and then deduplicating the result set with Distinct. Common when building read models that embed related entities.

Related errors


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