Just another tech site

C# LINQ to Entity


Some interesting elements about LINQ to Entities.
paging
dynamic query building

Paging

Let’s face it, in every situation we will need paging. Imaging that we want to show the data in tables.

public List<Client>
GetAllClients(bool? isActive, int pageNumber, int pageSize, out int totalPages)
{
//Actual query which returns large data
var query = dataContext.Clients.Where(p => isActive == null || p.IsActive == isActive);
 
//Calculating total number of pages by taking ceiling number of the fractional value
totalPages = (int)Math.Ceiling((decimal)query.Count() / (decimal)pageSize);
 
//Paging logic goes here
return query.Skip((pageNumber - 1)*pageSize).Take(pageSize).ToList();
}

Reference

[1]

Leave a comment