.netasp.net-coreentity-framework-corepaginationkeyset-pagination

Keyset pagination in Ef core 7


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


Solution

  • For Guids, you should use the string.CompareTo method which is understood and translated properly by EFCore. Something like this should work:

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

    I do this in MR.EntityFrameworkCore.KeysetPagination for example, which is a package that simplifies using keyset pagination with EFCore. The link contains the code where I dynamically generate these expressions. This is the library you linked in the comment. If there's something not clear in the implementation and you want to understand more I don't mind answering if you open a GitHub issue.