user3456014
user3456014

Reputation:

Entity Framework - counting entries

Adding pagination to a (dotnet EntityFramework Core) table of db entities, I'd like to show a message like 'Showing items X to Y of Z' where Z is the total number of items in the table being paged.

Currently I fetch that total number of entries from a DbSet in a DbContext as dbContext.Things.Count().

On the plus side, this works (modulo possible ongoing parallel updates to the table of Things, but that's close enough for me).

On the down side, I'm concerned that it might not be particularly efficient, even that it might try to load items into memory. Clearly, with pagination I will need to load only a handful of items to display the current page.

My database is postgresql 9.5, accessed via Npsql.

So my question is: does anyone know of any pitfalls with this approach?

Upvotes: 1

Views: 63

Answers (1)

user3456014
user3456014

Reputation:

It turns out that for Postgres, Count could be an O(n) operation after all... https://wiki.postgresql.org/wiki/Count_estimate

There are tricks to try here which involve executing SQL at a penalty of producing estimates and/or slowing writes.

This table of mine is written far more often than it is read, so a naïve Count will do for the time being.

Upvotes: 1

Related Questions