rimes rimes - 5 months ago 16x
SQL Question

C# Entity Framwork - Order by and Take

I am trying to select 5 oldest entries from my database. I am using the following statement:

dbContext.Items.Take(5).OrderBy(i => i.LastCheck).ToListAsync();

The problem here is that EF first takes the first 5 Items from the table, and then sorts them. So I always get the 5 first entries from the table. But i want it first to sort the items and then select the top 5 ones, like when i execute this sql command:

select top 5 * from Items order by LastCheck asc

Here i get the right result.

Is there a possibility to do that in EF or do i have to execute the query ?



you have to switch Take() and OrderBy()

dbContext.Items.OrderBy(i => i.LastCheck).Take(5).ToListAsync();