I have having trouble with this data paging script. I get the error System.Int64 to type System.Int32. The logs do not say anything useful. Call Stack has nothing. This line long long totalRecipes = await recipesQuery.LongCountAsync(); should show Int64. I have tried different ways of coding but no luck still say the same error message.
public class RecipeController : Controller
{
private readonly ApplicationDbContext _context;
private readonly ILogger<RecipeController> _logger;
public RecipeController(ApplicationDbContext context, ILogger<RecipeController> logger)
{
_context = context;
_logger = logger;
}
public async Task<IActionResult> Index(string searchString, int? page)
{
ViewData["CurrentFilter"] = searchString;
int pageSize = 10; // Display 10 recipes per page
int pageNumber = (page ?? 1);
var recipesQuery = _context.Recipes.AsQueryable();
if (!string.IsNullOrEmpty(searchString))
{
recipesQuery = recipesQuery.Where(r => r.RecipeTitle != null && r.RecipeTitle.Contains(searchString));
}
try
{
long totalRecipes = await recipesQuery.LongCountAsync();
_logger.LogInformation($"Total Recipes: {totalRecipes}");
var recipes = await recipesQuery
.OrderBy(r => r.RecipeID)
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
_logger.LogInformation($"Recipes Count: {recipes.Count}");
var totalPages = (int)Math.Ceiling(totalRecipes / (double)pageSize);
var viewModel = new RecipePagination
{
Recipes = recipes,
CurrentPage = pageNumber,
TotalPages = (int)Math.Ceiling(totalRecipes / (double)pageSize),
PageSize = pageSize,
SearchString = searchString
};
return View(viewModel);
}
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred while fetching the recipes.");
throw;
}
}
}