我有以下查询:
var content = (from ca in db.ContentAccesses
where !candidateList.Contains(ca.Content) &&
ca.DateAccessed >= DateTime.Now.AddDays(-90)
group ca by ca.ContentId)
.OrderByDescending(c => c.Count()).Take(5);
哪个解析为以下T-SQL
SELECT TOP (5) [t1].[ContentId] AS [Key]
FROM (
SELECT COUNT(*) AS [value], [t0].[ContentId]
FROM [dbo].[ContentAccesses] AS [t0]
WHERE (NOT ([t0].[ContentId] = @p0)) AND ([t0].[DateAccessed] >= @p1)
GROUP BY [t0].[ContentId]
) AS [t1]
ORDER BY [t1].[value] DESC
但我需要实际的“内容”对象,而不仅仅是ContentId ...所以我尝试在select ca.Content
之后添加group by
,但编译器会抱怨。
ContentAcceses有一个FK(ContentId)到内容表。
我还不太了解LINQ。
答案 0 :(得分:2)
您需要向下展平分组以从组中获取单个对象。但是,由于您希望对每个ContentAccess
的{{1}}进行分组,因此您也应将其分组。
Content
为了获得更简单的等效TSQL查询,您可能希望使用LINQ to Objects进行展平并获得前5个。
var content = (from ca in db.ContentAccesses
where !candidateList.Contains(ca.Content)
&& ca.DateAccessed >= DateTime.Now.AddDays(-90)
group ca by ca.ContentId into g
orderby g.Count() descending
from ca in g // flatten the group
select ca)
.Take(5);
答案 1 :(得分:0)
var content = (from ca in db.ContentAccesses
where !candidateList.Contains(ca.Content) &&
ca.DateAccessed >= DateTime.Now.AddDays(-90)
group ca by ca.ContentId into cag
select new
{
ContentId = cag.Key,
Contents = cag
}).OrderByDescending(c => c.Contents.Count()).Take(5);