简体   繁体   English

具有Distinct过滤器的Entity Framework 6查询

[英]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: 我想知道是否可以使“ Distinct”与查询一起运行,如下所示:

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: 要获取您要查询的查询,您需要先调用Select然后再调用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 更新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 更新2

Now I tested the first query in LinqPad in another context but using the same idea: 现在,我在另一个上下文中使用相同的思想在LinqPad中测试了第一个查询:

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: 这是生成的sql:

-- 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: 对要通过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: 这是SQL代码:

-- 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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