Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to Entities - DISTINCT on one column

Is there a way to write following query with Linq to Entities (or Entity SQL, or Method Syntax, or any other way, but I would like to achieve it with Linq to Entities):

SELECT DISTINCT Column1
FROM Table1

I'm using Entity Framework 4. Of course I don't want to use Distinct method that filters data after data is fetched from database.

thanks,Pawel

like image 835
dragonfly Avatar asked Dec 12 '11 11:12

dragonfly


1 Answers

Use something like

db.Table1.Select(t => t.Column1).Distinct()

As Munim mentioned in his comment, the Distinct() method does add the DISTINCT to the query. So resulting SQL query will be

SELECT [Distinct1].[Column1] AS [Column1]
  FROM ( SELECT DISTINCT 
    [Extent1].[Column1] AS [Column1]
    FROM [dbo].[Table1] AS [Extent1]
  )  AS [Distinct1]
like image 172
okrumnow Avatar answered Oct 06 '22 01:10

okrumnow