All of the answers so far do this in two queries. I think this is bad, and due to the wonders of SQL optimisation theres a little hack you can do to avoid needing to do a second query for the count in pagination.
Instead of doing the second query for count, append the count to each row and then separate it in the result set.
Below is a little helper I wrote to help do this:
public static IQueryable<EntityWithCount<T>> GetWithTotal<T>(this IQueryable<T> entities, int page, int pageSize) where T : class
{
return entities
.Select(e => new EntityWithCount<T> { Entity = e, Count = entities.Count() })
.Skip((page-1) * pageSize)
.Take(pageSize);
}
public class EntityWithCount<T> where T : class
{
public T Entity { get; set; }
public int Count { get; set; }
}
Full source on github
This method is faster for reasonable page sizes and avoids any transactional issues you might have doing multiple queries.
You you can chain this at the end of any other un-enumerated query (such as the one in the question, replacing the skip/take and before the .ToListAsync()
call)