Implementation of [PARTITION BY] command by LINQ

妖精的绣舞 提交于 2021-02-17 06:06:31

问题


I did my best search to convert PARTION BY command from TSQL to LINQ command. But apparently there is no way to convert it.
This is my code to which I am going to convert:

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

If exist any solution I would be greatful to know.


回答1:


linq2db has this feature among with CTE. If you already work with EF Core, you can extend your LINQ queries by extension linq2db.EntityFrameworkCore

This SQL can be written by 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;
         

I have simplified your OrderBy - CustomerID is not needed if you are making partition by this field.



来源:https://stackoverflow.com/questions/64412492/implementation-of-partition-by-command-by-linq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!