using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using NpgsqlTypes; using Pf2eModel; using Pf2eModel.Model.Base; using Pf2eModel.Model.Enum; namespace Pf2eWeb.Pages { public class EntityTypeModel : PageModel { private readonly Pf2eDbContext _context; public EntityTypeModel(Pf2eDbContext context) { _context = context; } [BindProperty(SupportsGet = true)] public int? PageNum { get; set; } public IList Entity { get; set; } = default!; public EntityType CurrentType; public int LastPage; public int CurrentPage => PageNum ?? 1; public const int PerPage = 30; public void OnGet(string type) { CurrentType = Enum(type); int count = _context.Entities.Count(entity => entity.Type == CurrentType); LastPage = (int)Math.Ceiling(count / (double)PerPage); Entity = _context .Entities.Where(entity => entity.Type == CurrentType) .Skip((CurrentPage - 1) * PerPage) .Take(PerPage) .ToList(); } /// /// Преобразование значения из JSON в перечисление. /// /// Значение, которое нужно преобразовать /// Объект типа `T`, если преобразование успешно, иначе выбрасывает исключение public static T Enum(string value) where T : Enum { foreach (System.Reflection.FieldInfo field in typeof(T).GetFields()) { List variants = [field.Name]; if ( Attribute.GetCustomAttribute(field, typeof(PgNameAttribute)) is PgNameAttribute pgAttribute ) { variants.Add(pgAttribute.PgName); } if (variants.Contains(value)) { return (T)field.GetValue(null)!; } } throw new Exception($"Can't resolve enum value \"{value}\" for type {typeof(T)}"); } public List Pagination { get { List pages = [1]; int start = Math.Max(2, CurrentPage - 1); int end = Math.Min(LastPage - 1, CurrentPage + 1); if (start > 2) pages.Add(-1); for (int i = start; i <= end; i++) pages.Add(i); if (end < LastPage - 1) pages.Add(-1); if (LastPage > 1) pages.Add(LastPage); return pages; } } } }