public class GenericRepository : IGenericRepository where T : class where TKey : IEquatable { protected readonly ApplicationDbContext Context; protected readonly IMapper Mapper; protected GenericRepository(ApplicationDbContext context, IMapper mapper) { Context = context; Mapper = mapper; } public async Task GetAsync(TKey id) { if (id == null) return null; return await Context.Set().FindAsync(id); } public async Task GetAsync(TKey id) { if (id == null) return default; // return await Context.Set().FindAsync(id); return Mapper.Map(await Context.Set().FindAsync(id)); } public async Task> GetAllAsync() { return await Context.Set().ToListAsync(); } public async Task> GetAllAsync(QueryParameters queryParameters) where TResult : class { var totalCount = await Context.Set().CountAsync(); var totalPages = (int)Math.Ceiling((decimal)totalCount / queryParameters.PageSize); var items = await Context.Set().AsQueryable() .Order(queryParameters.SortField, queryParameters.SortDirection) .Skip((queryParameters.Page - 1) * queryParameters.PageSize) .Take(queryParameters.PageSize) .ProjectTo(Mapper.ConfigurationProvider) .ToListAsync(); return new PagedResponse { Items = items, TotalCount = totalCount, TotalPages = totalPages, Page = queryParameters.Page, PageSize = queryParameters.PageSize }; } public async Task AddAsync(T entity) { await Context.AddAsync(entity); await Context.SaveChangesAsync(); return entity; } public async Task UpdateAsync(T entity) { Context.Update(entity); Context.Entry(entity).State = EntityState.Modified; await Context.SaveChangesAsync(); } public async Task DeleteAsync(TKey id) { var entity = await GetAsync(id); if (entity == null) return; Context.Set().Remove(entity); await Context.SaveChangesAsync(); } public async Task ExistsAsync(TKey id) { var entity = await GetAsync(id); return entity != null; } }