Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter a query based on row number using LINQ with Entity Framework

I have the following query in MySQL (version 8+)

SELECT MachineId, TotalProduction
FROM (
    SELECT MachineId,
           TotalProduction,
           ROW_NUMBER() OVER (PARTITION BY DATE(InsertedAt) ORDER BY InsertedAt DESC) AS rn
    FROM Machines
) AS a
WHERE rn = 1;

I want to translate this query to a LINQ query. I’m using Entity Framework Core 8.0.6.

I have already read this and this answers, but none of them are using the row number as a parameter to filter, only to select. How can I translate the SQL query to Entity Framework Core with LINQ, including filtering based on the row number?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can select directly out of a grouped query using .First. This should in theory be translated to a ROW_NUMBER query.

var query =
    from m in db.Machines
    group by m.InsertedAt.Date into g
    select g.OrderByDescending(m2 => m2.InsertedAt).First();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading