在EntityFramework中获取每个组的最后一条记录?

11
我想要从实体框架中检索每个MobileNo的最后插入记录。 这是我的表数据。
ID      RegNo       MobileNo    CreatedDate
26727   190077348   9696562673  13-02-2017 06:31
26729   123782783   9696562673  13-02-2017 06:35
45779   530087328   5878525875  07-02-2017 07:23
99902   120058572   7379130560  08-02-2017 12:39
64477   180073650   7417516480  10-02-2017 13:47
81839   240087264   7754990580  11-02-2017 10:47 

并且希望输出如下

ID      RegNo       MobileNo    CreatedDate 
26729   123782783   9696562673  13-02-2017 06:35
45779   530087328   5878525875  07-02-2017 07:23 
99902   120058572   7379130560  08-02-2017 12:39
64477   180073650   7417516480  10-02-2017 13:47
81839   240087264   7754990580  11-02-2017 10:47 
2个回答

29
假设您的表名为Items
var result = dbContext.Items.GroupBy(x => x.MobileNo)
                      .Select(x => x.OrderByDescending(y => y.CreatedDate).First());

运行示例:https://dotnetfiddle.net/3ud2pB


4
解决方案在 EF Core 上无法工作,能否提供关于 EF Core 的示例代码?谢谢。 - sebu
如果我遇到的是同样的错误,那么原因是它无法将linq转换为sql。 - RagnaRock
@sebu,你找到了EF Core的解决方案吗? - cikatomo
@cikatomo,你可以查看这个教程:https://medium.com/@pawel.gerr/entity-framework-core-row-number-support-54ac3392f69dROW_NUMBER和PARTITION在DbFunctions中没有实现。文档:https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbfunctions?view=efcore-6.0 - sebu

-1

试一下这个。

;WITH cte AS
(
   SELECT *,
         ROW_NUMBER() OVER (PARTITION BY MobileNo ORDER BY CreatedDate DESC) AS rn
   FROM yourtablename
)
SELECT *
FROM cte
WHERE rn = 1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接