简体   繁体   中英

Entity Framework 6 query with Distinct filter

I have a problem. When I run the code below:

var data = context.TableX.Where(w => w.userId == 9999&& w.id == 9999) .Distinct().ToList();

This is the query generated:

SELECT [Extent1].[id] AS [id], [Extent1].[name] AS [name], [Extent1].[companyId] AS [companyId], [Extent1].[userId] AS [userId] FROM [TableX] AS [Extent1] WHERE (9999 = [Extent1].[userId]) AND (9999= [Extent1].[id]) -- Executing at 01/06/2016 17:28:01 -03:00 -- Completed in 271 ms with result: SqlDataReader

I wonder if you can make the "Distinct" to run with the query as follows:

SELECT DISTINCT id, name, companyId AS type FROM TableX WHERE id=9999 AND userId=9999

Thanks.

To obtain the query you want you need to call first a Select before call Distinct to get only the columns you need to apply a distinct:

var data = context.TableX.Where(w => w.userId == 9999&& w.id == 9999)
                         .Select(e=>new {e.id, e.name, e.companyId}) 
                         .Distinct()
                         .ToList();

Update 1

I'm pretty sure the first query should work but anyways another solution could be applying a group by:

var data = context.TableX.Where(w => w.userId == 9999&& w.id == 9999)
                         .GroupBy(e=>new {e.id, e.name, e.companyId}) 
                         .Select(g=>new{g.Key.id, g.Key.name, g.Key.companyId})
                         .ToList();

Update 2

Now I tested the first query in LinqPad in another context but using the same idea:

var query=Agencies.Where(a=>a.StatusId==1)
                  .Select(e=>new{e.StateId, e.AgencyName})
                  .Distinct()
                  .Dump();

And this is the sql that was generated:

-- Region Parameters
DECLARE @p0 Int = 1
-- EndRegion
SELECT DISTINCT [t0].[stateId] AS [StateId], [t0].[agencyName] AS [AgencyName]
FROM [Agencies] AS [t0]
WHERE [t0].[statusId] = @p0

As you can see, it should work, I don't really know what is happening in your case.

Repeating the same process to the second query to be executed via LinqPad:

var query=Agencies.Where(a=>a.StatusId==1)
                  .GroupBy(e=>new{e.StateId, e.AgencyName})
                  .Select(g=>new{g.Key.StateId, g.Key.AgencyName})
                  .Dump();

And this is the sql code:

-- Region Parameters

DECLARE @p0 Int = 1
-- EndRegion
SELECT [t0].[stateId] AS [StateId], [t0].[agencyName] AS [AgencyName]
FROM [Agencies] AS [t0]
WHERE [t0].[statusId] = @p0
GROUP BY [t0].[stateId], [t0].[agencyName]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM