Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 990
Guilherme Santana Avatar asked Nov 23 '25 13:11

Guilherme Santana


2 Answers

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();
like image 138
Charlieface Avatar answered Nov 25 '25 03:11

Charlieface


var query = context.Machines
    .GroupBy(m => m.InsertedAt.Date)
    .Select(g => g.OrderByDescending(m => m.InsertedAt).FirstOrDefault())
    .Select(m => new 
    {
        m.MachineId,
        m.TotalProduction
    })
    .ToList();

Try this solution out

like image 32
Antony Mathew Avatar answered Nov 25 '25 04:11

Antony Mathew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!