Home > Software design >  How to reverse a paged datasource using EF core?
How to reverse a paged datasource using EF core?

Time:07-31

I use the following code to get paged data in the data grid (EF Core 6):

using (var _sqliteContext = new SQLiteContext())
{
   AssociatedObject.LoadDynamicItems(e.StartIndex, await _sqliteContext.Equipments
                   .Include(x => x.CostCenter)
                   .Include(x => x.EqInfo)
                   .Skip(e.StartIndex)
                   .Take(e.PageSize)
                   .ToListAsync());
}

I want to reverse the order of the whole data meaning the last data added is shown on the first page by default. I tried to use .TakeLast(e.PageSize) but It causes a runtime error and cannot be translated.

How can I do it?

Update: I want the newer data to be on the first pages. New data are detected based on incrementing IDs.

CodePudding user response:

Order the records in your query before you attempt to page it. You've said that the higher the Id column is (some number), the newer it is.

await _sqliteContext.Equipments
    .Include(x => x.CostCenter)
    .Include(x => x.EqInfo)
    .OrderByDecending(x => x.Id) // <- ordering results, newest first
    .Skip(e.StartIndex)
    .Take(e.PageSize)
    .ToListAsync());
  • Related