Keyset pagination in Ef core 7

919 Views Asked by At

i have been reading this https://learn.microsoft.com/th-th/ef/core/querying/pagination from EFCore team tried to implement it. The problem i am facing with is the example shown here is using a primary key of type INT. in my entity class given below the primary is of type GUID

public sealed class Company{
    public Guid Id { get; set; }
    public DateTimeOffset CreatedOn { get; set; }
    public string? CreatedBy { get; set; }

    public string Name { get; private set; } = null!;
    public string Email { get; private set; } = null!;
    public string? ContactNumber { get; private set; }
    public string? Address { get; private set; }
    public string QBAccount { get; private set; } = null!;
    public string BoxFolderPath { get; private set; } = null!;
}

i tried to implement this with the same condition where given in the example in the link which is to compare the pk in the Where() clause as

var lastId = Guid.Parse("42ce0165-62b8-4ef6-f62f-08dadc0d2e5d");
var nextPage = context.Posts
    .OrderBy(b => b.PostId)
    .Where(b => b.PostId > lastId)
    .Take(10)
    .ToList();

but i dont get the expected pagination result. any help please

1

There are 1 best solutions below

3
Ben On

You're ordering by a Guid, which are not sequential by default. There are ways to generate sequential guids, but I'm not sure that would fix your ordering in a reliable way.

I believe it is better to order by another property that represents your data in an orderly fashion. I see you have a CreatedOn property. When you would order by that property, you should get the same kind of results as ordering by an integer ID property.

It could introduce new kind of problems, your .Where clause will be different. It could change to the last CreatedOn value or you can create a subquery to retrieve the CreatedOn value of the lastId record.