dotnet / ef6

This is the codebase for Entity Framework 6 (previously maintained at https://entityframework.codeplex.com). Entity Framework Core is maintained at https://github.com/dotnet/efcore.

Home Page:https://docs.microsoft.com/ef/ef6

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Group By and Distict do not work for multiple columns

Coder3333 opened this issue · comments

I am not seeing the expected sql generated for Linq to SQL with regard to Distinct when selecting multiple columns. In particular the Distinct is being left out of the generated SQL. Strangely, this seems to work properly when my Select clause only has 1 column. How do I achieve a Distinct SQL query using Entity Framework when selecting multiple columns? Group By also does not work when the key is multiple columns.

Query that selects multiple columns ignores Distinct:

 var distinct1 = e.MyViews
                .Select(a => new { a.Col1, a.Col2, a.Col3, })
                .Distinct()
                    .ToList();

Generated SQL is missing Distinct:

SELECT 
    [Extent1].[Col1] AS [Col1], 
    [Extent1].[Col2] AS [Col2], 
    [Extent1].[Col3] AS [Col3]
    FROM (SELECT 
    [MyView].[Col1] AS [Col1], 
    [MyView].[Col2] AS [Col2], 
    [MyView].[Col3] AS [Col3], 
    [MyView].[UserId] AS [UserId]
    FROM [MySchema].[MyView] AS [MyView]) AS [Extent1]

Query that selects single column uses Distinct:

var distinct2 = e.MyViews
.Select(a => new { a.Col1, })
.Distinct()
    .ToList();

Generated SQL correcty includes Distinct:

SELECT 
    [Distinct1].[C1] AS [C1], 
    [Distinct1].[Col1] AS [Col1]
    FROM ( SELECT DISTINCT 
        [Extent1].[Col1] AS [Col1], 
        1 AS [C1]
        FROM (SELECT 
    [MyView].[Col1] AS [Col1], 
    [MyView].[Col2] AS [Col2], 
    [MyView].[Col3] AS [Col3], 
    [MyView].[UserId] AS [UserId]
    FROM [MySchema].[MyView] AS [MyView]) AS [Extent1]
    )  AS [Distinct1]	

Update

I am now finding that some combinations of columns in the Select clause do work, while others do not, but I cannot determine what the differentiating factor is.

These combinations of columns in Select do produce Distinct in SQL:
Col1
Col2
Col3
Col1, Col2
Col2, Col3

These combinations of columns in Select do not produce Distinct in SQL:
Col1, Col3
Col1, Col2, Col3

This issue has been closed because EF6 is no longer being actively developed. We are instead focusing on stability of the codebase, which means we will only make changes to address security issues. See the repo README for more information.