1

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

thanzeel
  • 431
  • 4
  • 12
  • 1
    Real implementation is complex. You have to understand that `OrderBy` values has to be unique key. Also how do you plan to return cursor to the frontend? How to serialize. – Svyatoslav Danyliv Jan 16 '23 at 10:36
  • 2
    This page in docs makes it seem that sorting by Guid doesn't really work correctly: https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/comparing-guid-and-uniqueidentifier-values – juunas Jan 16 '23 at 10:40
  • i have found this https://github.com/mrahhal/MR.EntityFrameworkCore.KeysetPagination, it has tests for paging based on guid. but, its not very clear. the examples are not available. – thanzeel Jan 16 '23 at 11:06
  • Haven't tested it myself, but maybe this helps? https://stackoverflow.com/questions/54920200/entity-framework-core-guid-greater-than-for-paging – AnorZaken Mar 07 '23 at 12:51

1 Answers1

0

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.

Ben
  • 123
  • 6