如何在Linq to SQL中使用distinct with group

我正在尝试将以下sql转换为Linq 2 SQL:

select groupId, count(distinct(userId)) from processroundissueinstance group by groupId 

这是我的代码:

 var q = from i in ProcessRoundIssueInstance group i by i.GroupID into g select new { Key = g.Key, Count = g.Select(x => x.UserID).Distinct().Count() }; 

当我运行代码时,我一直收到Invalid GroupID。 有任何想法吗? 看起来不同的是搞砸了……

这是生成的sql:

 SELECT [t1].[GroupID] AS [Key], ( SELECT COUNT(*) FROM ( SELECT DISTINCT [t2].[UserID] FROM [ProcessRoundIssueInstance] AS [t2] WHERE (([t1].[GroupID] IS NULL) AND ([t2].[GroupID] IS NULL)) OR (([t1].[GroupID] IS NOT NULL) AND ([t2].[GroupID] IS NOT NULL) AND ([t1].[GroupID] = [t2].[GroupID])) ) AS [t3] ) AS [Count] FROM ( SELECT [t0].[GroupID] FROM [ProcessRoundIssueInstance] AS [t0] GROUP BY [t0].[GroupID] ) AS [t1] 

我认为Basiclife很接近,但是检查id是否为空可能不是问题或者足够,你应该检查以确保它在执行组之前不是null,因为你说它是一个可以为空的字段。 否则它看起来是正确的,如果你遇到问题,你可能有错误的数据,或者它是一个错误或没有完全实现Linq to SQL的function,你可能想尝试Linq to Entity。

 var q = from i in ProcessRoundIssueInstance where i.GroupID != null && i.GroupID != string.Empty group i by i.GroupID into g select new { Key = g.Key, Count = g.Select(x => x.UserID).Distinct().Count() }; 

根据这篇文章,您的代码看起来正确:

使用GROUP BY和COUNT(DISTINCT)的LINQ to SQL

您是否尝试检查生成的SQL?

在生成的SQL中似乎有一大堆goop来处理GroupID为NULL。 如果可能的话? 如果没有,请尝试更改定义以使其为NOT NULL。

尝试使用where子句来消除连接后的虚假ID …

 var q = from i in ProcessRoundIssueInstance where i.GroupID != "" group i by i.GroupID into g select new { Key = g.Key, Count = g.Select(x => x.UserID).Distinct().Count() }; 

您确定数据库完整性正确吗? 无论如何也许你应该试试这个:我不知道一个小组是如何空的,但这似乎是你的问题。

 ProcessRoundIssueInstance.Where(i => i.GroupId != null) .GroupBy(i => i.GroupID) .Select(group => new { Key = group.Key, Count = group.SingleOrDefault() == null ? 0 : group.SingleOrDefault().Select( item => item.UserID).Distinct().Count() });