Repository.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using Azure;
  2. using Microsoft.AspNetCore.Mvc.RazorPages;
  3. using Microsoft.EntityFrameworkCore;
  4. using MTWorkHR.Core.Entities.Base;
  5. using MTWorkHR.Core.IDto;
  6. using MTWorkHR.Core.IRepositories.Base;
  7. using MTWorkHR.Infrastructure.Data;
  8. using System.Linq;
  9. using System.Linq.Dynamic.Core;
  10. namespace MTWorkHR.Infrastructure.Repositories
  11. {
  12. public class Repository<T> : IRepository<T> where T : Entity
  13. {
  14. protected readonly HRDataContext _context;
  15. private readonly DbSet<T> dbSet;
  16. public Repository(HRDataContext context)
  17. {
  18. _context = context;
  19. dbSet = context.Set<T>();
  20. }
  21. public async Task<T> AddAsync(T entity)
  22. {
  23. await _context.AddAsync(entity);
  24. await _context.SaveChangesAsync();
  25. return entity;
  26. }
  27. public async Task<IList<T>> AddRangeAsync(IList<T> entities)
  28. {
  29. await dbSet.AddRangeAsync(entities);
  30. return entities;
  31. }
  32. public async Task DeleteAsync(T entity)
  33. {
  34. dbSet.Remove(entity);
  35. }
  36. public async Task DeleteRangeAsync(IEnumerable<T> entities)
  37. {
  38. dbSet.RemoveRange(entities);
  39. }
  40. public async Task<Tuple<ICollection<T>, int>> GetAllAsync()
  41. {
  42. var query = dbSet.AsQueryable();
  43. var total = await query.CountAsync();
  44. return new Tuple<ICollection<T>, int>(await query.ToListAsync(), total);
  45. }
  46. public virtual async Task<Tuple<ICollection<T>, int>> GetAllAsync(IPagingInputDto pagingInputDto)
  47. {
  48. var query = dbSet.AsQueryable();
  49. if (pagingInputDto.HiddenFilter != null)
  50. {
  51. query = query.Where(pagingInputDto.HiddenFilter);
  52. }
  53. if (pagingInputDto.Filter != null)
  54. {
  55. var props = typeof(T).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(FilterAttribute)));
  56. var condition = "";
  57. foreach (var p in props)
  58. {
  59. condition = (condition == "" ? condition : condition + " || ") + p.Name + ".Contains(@0)";
  60. }
  61. query = query.Where(condition, pagingInputDto.Filter);
  62. }
  63. var order = query.OrderBy(pagingInputDto.OrderByField + " " + pagingInputDto.OrderType);
  64. var page = order.Skip((pagingInputDto.PageNumber * pagingInputDto.PageSize) - pagingInputDto.PageSize).Take(pagingInputDto.PageSize);
  65. var total = await query.CountAsync();
  66. return new Tuple<ICollection<T>, int>(await page.ToListAsync(), total);
  67. throw new NotImplementedException();
  68. }
  69. public async Task<T> GetByIdAsync(long id)
  70. {
  71. return await _context.Set<T>().FindAsync(id);
  72. }
  73. }
  74. }