【问题标题】:Is there a function in Entity Framework that translates to the RANK() function in SQL?实体框架中是否有一个函数可以转换为 SQL 中的 RANK() 函数?
【发布时间】:2014-12-14 13:32:38
【问题描述】:

假设我想按国家/地区对我的客户数据库进行排名。在 SQL 中我会写:

select CountryID, CustomerCount = count(*), 
       [Rank] = RANK() over (order by count(*) desc)
from Customer

现在我想在实体框架中写这个:

var ranks = db.Customers
  .GroupBy(c => c.CountryID)
  .OrderByDescending(g => g.Count())
  .Select((g, index) => new {CountryID = g.Key, CustomerCount = g.Count, Rank = index+1});

这样做有两个问题:

  1. 它不起作用。 EF 抛出一个System.NotSupportedException;显然没有使用行号的overload of .Select() 的SQL 翻译;您必须使用.ToList() 将所有内容拉入内存才能调用此方法;和
  2. 即使您在本地内存中运行该方法,它也不会像 SQL 中的RANK() 函数那样处理相等的排名,即它们应该具有相等的排名,然后以下项目跳到原始顺序。

那我该怎么做呢?

【问题讨论】:

  • AKAIK Rank() 在 LINQ 中没有内置函数。这个答案使用了你的方法,但它似乎对他们有用:stackoverflow.com/a/21035060/7720 或者这个问题有几个选项。
  • @Romias 你让我找到this answer 解决了我的问题。请随时在此处将其写成答案,以便我给您好评!
  • 很高兴为您提供帮助...我将评论作为答案!谢谢!
  • 这有点奇怪......为什么有人会否决这个问题?

标签: c# sql-server-2012 entity-framework-5


【解决方案1】:

AFAIK Rank() 在 LINQ 中没有内置函数。 This answer 使用您的方法,但似乎对他们有用。以下是你可以如何使用它:

var customersByCountry = db.Customers
    .GroupBy(c => c.CountryID);
    .Select(g => new { CountryID = g.Key, Count = g.Count() });
var ranks = customersByCountry
    .Select(c => new 
        { 
            c.CountryID, 
            c.Count, 
            Rank = customersByCountry.Count(c2 => c2.Count > c.Count) + 1
        });

【讨论】:

  • 谢谢!我添加了一些代码,以便您可以看到它已应用。
猜你喜欢
  • 2014-02-21
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多