dotnet / dotnet/efcore

distinct is not performed within queries using projection

Open
#35,362 9 comments 0 reactions 0 assignees View on GitHub
area-query customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

### error description
When preparing a query projecting a single id column and using Distinct to avoid duplicate I expect to retrieve... well distinct results

### Include your code
```C#
var query = context.Affaires
.Where(a => a.StatutAffaire == StatutAffaire.Won)
.Where(a => a.ReferenceId == null)
.Where(a => listPassIds.Contains(a.EntityId))
;

var passIds = await query
.Select(a => a.PassId) // projection
.Distinct() // distinct
.ToArrayAsync(cancellationToken);
```

### expected query
```
exec sp_executesql N'SELECT DISTINCT [l].[PassId]
FROM [Link_Pass_AtlasAffaire] AS [l]
WHERE [l].[StatutAffaire] = 4 AND [l].[ReferenceId] IS NULL AND [l].[PassId] IN (
SELECT [l0].[value]
FROM OPENJSON(@__listPassIds_0) WITH ([value] uniqueidentifier ''$'') AS [l0]
)',N'@__listPassIds_0 nvarchar(4000)',@__listPassIds_0=N'["be8a8784-978d-4a68-9484-08dd095619d2","1579e349-0992-4a3b-6ee1-08dc9c32a29e"]'
```

### query produced
```
exec sp_executesql N'SELECT DISTINCT [l].[Id], [l].[AtlasId], [l].[PassId], [l].[LastControlDateTime], [l].[LastSendingDateTime], [l].[ReferenceId], [l].[AtlasGroupId], [l].[StatutAffaire]
FROM [Link_Pass_AtlasAffaire] AS [l]
WHERE [l].[StatutAffaire] = 4 AND [l].[ReferenceId] IS NULL AND [l].[PassId] IN (
SELECT [l0].[value]
FROM OPENJSON(@__listPassIds_0) WITH ([value] uniqueidentifier ''$'') AS [l0]
)',N'@__listPassIds_0 nvarchar(4000)',@__listPassIds_0=N'["be8a8784-978d-4a68-9484-08dd095619d2","1579e349-0992-4a3b-6ee1-08dc9c32a29e"]'
```

### my 2 cents
projection is made 'outside' of query scope making distinct work on all columns

### Include provider and version information

EF Core version:
```





```

Database provider: SqlServer 2022 on docker
Target framework: .NET 9
Operating system: Windows 11
IDE: Visual Studio 2022 17.12.3

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.