LINQ实现[PARTITION BY]命令

问题描述

我竭尽全力将PARTION BY命令从Tsql转换为LINQ命令。但是显然没有办法将其转换。
这是我要转换为的代码

WITH MyRowSet
AS
(
SELECT OrderDate,SalesOrderNumber,AccountNumber,CustomerID,ROW_NUMBER() OVER (PARTITION BY CustomerID ORDER BY CustomerID,OrderDate DESC) AS RowNum
FROM [Sales].[SalesOrderHeader] 
)
SELECT * FROM MyRowSet WHERE RowNum = 1

如果有任何解决方案,我将不胜感激。

解决方法

linq2db在CTE中具有此功能。如果您已经使用EF Core,则可以通过扩展linq2db.EntityFrameworkCore

扩展LINQ查询。

此SQL可以由LINQ编写

var rnQuery = 
    from oh in db.SalesOrderHeader
    select new 
    {
       oh.OrderDate,oh.SalesOrderNumber,oh.AccountNumber,oh.CustomerID,RowNum = Sql.Ext.RowNumber().Over().PartitionBy(oh.CustomerID)
          .OrderByDesc(oh.OrderDate).ToValue()
    };

// switch to alternative LINQ Translator
rnQuery = rnQuery.ToLinqToDB();

var query =
    from q in rnQuery.AsCte("MyRowSet")
    where q.RowNum == 1
    select q;
         

我已经简化了您的OrderBy-如果您要按此字段进行分区,则不需要CustomerID。