【问题标题】:How to translate this Queryable linq function如何翻译这个 Queryable linq 函数
【发布时间】:2013-01-20 06:50:16
【问题描述】:

我正在努力尝试在正确的 T-SQL 函数中生成此 LINQ 函数。

请检查以下句子:

// determine the max count of exams applied by students
IQueryable query = (from at in Database.Current.AnsweredTests
                    where at.TestId == id
                    group at by at.StudentId into s
                    select s.Count()).Max();

正如你所见,这个函数在语法上是错误的,因为Max 扩展返回int。所以我想要完成的是生成一个正确的 T-SQL。

类似这样的:

MAX(SELECT x.COUNT()
FROM...
GROUP BY StudentId)

我这样做只是因为我想要一个好的性能,而这就是性能低下。所以我的问题是如何使用 MAXCOUNT 等聚合函数编写正确的 LINQ 语句。

更新:

SELECT [GroupBy1].[A1] AS [C1]
FROM ( SELECT 
    [Extent1].[StudentId] AS [K1], 
    COUNT(1) AS [A1]
    FROM [dbo].[AnsweredTests] AS [Extent1]
    WHERE  CAST( [Extent1].[TestId] AS int) = @p__linq__0
    GROUP BY [Extent1].[StudentId]
)  AS [GroupBy1]

这就是生成 IQueryable 的原因(当然,如果我删除了最大扩展名)。我想知道是否有办法在该 T-SQL 查询中包含聚合函数 MAX 以提高服务器端的性能。

【问题讨论】:

  • 您的 IQueryable 生成的 SQL 是什么?
  • @DarfZon 你确定你想要的 SQL 是正确的吗?
  • @lazyberezovsky 当然,我错过了什么吗?
  • 旁注,但 CAST 看起来像一个丑陋的索引阻塞问题。不确定这是一个无法控制的工件,还是您在某处存在类型不匹配。

标签: c# linq entity-framework entity-framework-4


【解决方案1】:

您也可以用以下方式表达您的查询:

SELECT TOP 1 COUNT(*)
FROM AnsweredTests
WHERE TestId = @id
GROUP BY StudentId
ORDER BY COUNT(*) DESC

按照这个逻辑,这个(未经测试的)应该是你正在寻找的:

var result = (from at in Database.Current.AnsweredTests
              where at.TestId == id
              group at by at.StudentId into s
              orderby s.Count() descending
              select s.Count()).First()

【讨论】:

  • 我明白了,但是我的 LINQ FUNCTION 的输出类似于您发布的 T-SQL 代码,我该怎么做?
  • @DarfZon 对不起,我误解了你的问题。我以为你想要查询中的 T-SQL。
  • @DarfZon 已更新。如果它有效,这应该是您正在寻找的东西
【解决方案2】:

你可以先做ORDER BY DESCENDING然后先拿:

var Max = (from at in Database.Current.AnsweredTests
           where at.TestId == id
           group at by at.StudentId into s
           select new { Count = s.Count() }).OrderByDescending(o=>o.Count).First();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-29
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 2013-06-05
    相关资源
    最近更新 更多