Reputation: 53
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.
Upvotes: 5
Views: 12564
Reputation: 39386
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();
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();
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]
Upvotes: 6