我有问题。当我运行以下代码时:
var data = context.TableX.Where(w => w.userId == 9999&& w.id == 9999) .Distinct().ToList();
这是生成的查询:
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
我想知道你是否可以制作" Distinct"使用查询运行如下:
SELECT DISTINCT id, name, companyId AS type FROM TableX WHERE id=9999 AND userId=9999
感谢。
答案 0 :(得分:2)
要获得您想要的查询,您需要先致电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();
我非常确定第一个查询应该有效,但无论如何另一个解决方案可能是通过以下方式应用一个组:
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();
现在我在另一个上下文中测试了LinqPad中的第一个查询,但使用了相同的想法:
var query=Agencies.Where(a=>a.StatusId==1)
.Select(e=>new{e.StateId, e.AgencyName})
.Distinct()
.Dump();
这是生成的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
正如你所看到的,它应该有用,我真的不知道你的情况会发生什么。
将相同的过程重复到要通过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();
这是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]