The following are examples of pagination using EF.
- List By Page
- List By Page With a Filter/Where Clause
- List By Page Using a Join
*EF 5.0
*OrderBy Clause Required
//List By Page 1
public List<Entities.Object1> List(int page, int recordsPerPage)
{
int recordsToSkip = 0;
if (page <= 0)
{
page = 1;
}
recordsToSkip = (page - 1) * recordsPerPage;
return this.Db.Objects1.OrderBy(x => x.Id).Skip(recordsToSkip).Take(recordsPerPage).ToList();
}
//List By Page 1
public List<Entities.Object1> List(int page, int recordsPerPage)
{
int recordsToSkip = 0;
if (page <= 0)
{
page = 1;
}
recordsToSkip = (page - 1) * recordsPerPage;
var query = from objects in this.Db.Objects1
orderby objects.Id
select objects;
return query.Skip(recordsToSkip).Take(recordsPerPage).ToList();
}
//List By Page With a Filter/Where Clause 1
public List<Entities.Object1> List_By_StatusId(int statusId, int page, int recordsPerPage)
{
if (statusId > 0)
{
int recordsToSkip = 0;
if (page <= 0)
{
page = 1;
}
recordsToSkip = (page - 1) * recordsPerPage;
return this.Db.Objects1.Where(x => x.StatusId == statusId).OrderBy(x => x.Id).Skip(recordsToSkip).Take(recordsPerPage).ToList();
}
return new List<Entities.Object1>();
}
//List By Page With a Filter/Where Clause 2
public List<Entities.Object1> List_By_StatusId(int statusId, int page, int recordsPerPage)
{
if (statusId > 0)
{
int recordsToSkip = 0;
if (page <= 0)
{
page = 1;
}
recordsToSkip = (page - 1) * recordsPerPage;
var query = from objects in this.Db.Objects1
where objects.StatusId == statusId
orderby objects.Id
select objects;
return query.Skip(recordsToSkip).Take(recordsPerPage).ToList();
}
return new List<Entities.Object1>();
}
//List By Page Using a Join
public List<Entities.Object1> List_By_Object2StatusId(int object2StatusId, int page, int recordsPerPage)
{
if (object2StatusId > 0)
{
int recordsToSkip = 0;
if (page <= 0)
{
page = 1;
}
recordsToSkip = (page - 1) * recordsPerPage;
var query = from objects1 in this.Db.Objects1
join objects2 in this.Db.Objects2 on objects1.Object2Id equals objects2.Id
where objects2.StatusId == object2StatusId
orderby objects1.Id
select objects1;
return query.Skip(recordsToSkip).Take(recordsPerPage).ToList();
}
return new List<Entities.Object1>();
}