using ErsatzTV.Core.Domain; using ErsatzTV.Infrastructure.Data; using Microsoft.EntityFrameworkCore; using static ErsatzTV.Application.ProgramSchedules.Mapper; namespace ErsatzTV.Application.ProgramSchedules; public class GetPagedProgramSchedulesHandler(IDbContextFactory dbContextFactory) : IRequestHandler { public async Task Handle( GetPagedProgramSchedules request, CancellationToken cancellationToken) { await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken); IQueryable query = dbContext.ProgramSchedules.AsNoTracking(); if (!string.IsNullOrWhiteSpace(request.Query)) { query = query.Where(ps => EF.Functions.Like(ps.Name, $"%{request.Query}%")); } // count the SAME query the page is taken from, so the two cannot drift (issues #690, #758) int count = await query.CountAsync(cancellationToken); List page = await query .OrderBy(ps => ps.Name) .Skip(request.PageNum * request.PageSize) .Take(request.PageSize) .ToListAsync(cancellationToken) .Map(list => list.Map(ProjectToViewModel).ToList()); return new PagedProgramSchedulesViewModel(count, page); } }