{"record":{"id":"d239dda6d6e6df8b","repo":"dotnet/efcore","slug":"using-distinct-operation-on-a-projection-contain","errorCode":null,"errorMessage":"Using 'Distinct' operation on a projection containing a subquery is not supported.","messagePattern":"Using 'Distinct' operation on a projection containing a subquery is not supported\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.InMemory/Query/Internal/InMemoryQueryExpression.cs","lineNumber":515,"sourceCode":"\n        var selectorExpressions = new List<Expression>();\n        if (_clientProjections.Count == 0)\n        {\n            selectorExpressions.AddRange(_projectionMappingExpressions);\n            if (selectorExpressions.Count == 0)\n            {\n                // No server correlated term in projection so add dummy 1.\n                selectorExpressions.Add(Constant(1));\n            }\n        }\n        else\n        {\n            for (var i = 0; i < _clientProjections.Count; i++)\n            {\n                var projection = _clientProjections[i];\n                if (projection is InMemoryQueryExpression)\n                {\n                    throw new InvalidOperationException(InMemoryStrings.DistinctOnSubqueryNotSupported);\n                }\n\n                if (projection is EntityProjectionExpression entityProjectionExpression)\n                {\n                    _clientProjections[i] = TraverseEntityProjection(\n                        selectorExpressions, entityProjectionExpression, makeNullable: false);\n                }\n                else\n                {\n                    selectorExpressions.Add(projection);\n                    _clientProjections[i] = CreateReadValueExpression(\n                        projection.Type, selectorExpressions.Count - 1, InferPropertyFromInner(projection));\n                }\n            }\n        }\n\n        var selectorLambda = Lambda(\n            New(","sourceCodeStart":497,"sourceCodeEnd":533,"githubUrl":"https://github.com/dotnet/efcore/blob/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.InMemory/Query/Internal/InMemoryQueryExpression.cs#L497-L533","documentation":"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.","triggerScenarios":"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().","commonSituations":"Projecting correlated/related data and then deduplicating the result set with Distinct. Common when building read models that embed related entities.","solutions":["Remove the subquery from the projection before calling Distinct.","Call AsEnumerable() before Distinct to deduplicate client-side.","Apply Distinct to a simpler projection first, then load related data separately."],"exampleFix":"// before\nvar q = db.Blogs\n    .Select(b => new { b, Posts = b.Posts.ToList() })\n    .Distinct();\n// after\nvar q = db.Blogs.Distinct()\n    .Select(b => new { b, Posts = b.Posts.ToList() });","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"try\n{\n    var r = query.Select(projWithSubquery).Distinct().ToList();\n}\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"Distinct\"))\n{\n    var r = query.AsEnumerable().Select(projWithSubquery).Distinct().ToList();\n}","preventionTips":["Do not place subqueries in a projection you intend to Distinct.","Apply Distinct to a simpler projection and load related data afterward.","Use AsEnumerable() before Distinct when subqueries are unavoidable."],"tags":["ef-core","in-memory-provider","linq-translation","distinct","subquery"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}