Create a .NET Core Web API Project:
public class Employee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EmpId { get; set; }
[Required]
public string EmpName { get; set; }
public string Designation { get; set; }
public string Department { get; set; }
public string JoinDate { get; set; }
}
public class PagedList<T>:List<T>
{
public int CurrentPage { get; private set; }
public int TotalPages { get; private set; }
public int PageSize { get; private set; }
public int TotalCount { get; private set; }
public bool HasPrevious => CurrentPage > 1;
public bool HasNext => CurrentPage < TotalPages;
public PagedList(List<T> items,int count, int pageNumber, int pageSize)
{
TotalCount = count;
PageSize = pageSize;
CurrentPage = pageNumber;
TotalPages = (int)Math.Ceiling(count / (double)pageSize);
AddRange(items);
}
public static PagedList<T> GetPagedList(IQueryable<T> source,int pageNumber,int pageSize)
{
var count = source.Count();
var items = source.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();
return new PagedList<T>(items, count, pageNumber, pageSize);
}
}
public class PagingParameters
{
const int maxPageSize = 50;
public int PageNumber { get; set; } = 1;
private int _pageSize = 10;
public int PageSize {
get
{
return _pageSize;
}
set
{
_pageSize = (value > maxPageSize) ? maxPageSize : value;
}
}
}
public interface IRepositoryBase<T>
{
IQueryable<T> FindAll();
}
public abstract class RepositoryBase<T> : IRepositoryBase<T> where T : class
{
protected ApplicationDBContext RepositoryContext { get; set; }
public RepositoryBase(ApplicationDBContext repositoryContext)
{
this.RepositoryContext = repositoryContext;
}
public IQueryable<T> FindAll()
{
return this.RepositoryContext.Set<T>()
.AsNoTracking();
}
}
public interface IEmployeeRepository : IRepositoryBase<Employee>
{
Task<PagedList<Employee>> GetEmployees(PagingParameter pagingParameter);
}
public class EmployeeRepository : RepositoryBase<Employee>, IEmployeeRepository
{
public EmployeeRepository(ApplicationDBContext repositoryContext)
: base(repositoryContext)
{
}
public Task<PagedList<Employee>> GetEmployees(PagingParameter pagingParameter)
{
return Task.FromResult(PagedList<Employee>.GetPagedList(FindAll().OrderBy(on => on.EmpName), pagingParameter.PageNumber, pagingParameter.PageSize));
}
}
services.AddScoped<IEmployeeRepository, EmployeeRepository>()
private IEmployeeRepository _emprepository;
public EmployeesController(ApplicationDBContext context, IEmployeeRepository emprepository)
{
_emprepository = emprepository;
_context = context;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Employee>>> GetEmployees([FromQuery] PagingParameter pagingParameter)
{
var emp= await _emprepository.GetEmployees(pagingParameter);
var metadata = new
{
emp.TotalCount,
emp.PageSize,
emp.CurrentPage,
emp.TotalPages,
emp.HasNext,
emp.HasPrevious
};
Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(metadata));
return Ok(emp);
}
Video Link:
0 Comments