RepositoryLog.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using Microsoft.EntityFrameworkCore;
  2. using MTWorkHR.Core.Entities.Base;
  3. using MTWorkHR.Core.IDto;
  4. using MTWorkHR.Core.IRepositories.Base;
  5. using MTWorkHR.Infrastructure.DBContext;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Reflection;
  10. using System.Text;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using System.Linq.Dynamic.Core;
  14. namespace MTWorkHR.Infrastructure.Repositories
  15. {
  16. public class RepositoryLog<T>: IRepositoryLog<T> where T : class
  17. {
  18. protected readonly HRDataContext context;
  19. private readonly DbSet<T> dbSet;
  20. public RepositoryLog(HRDataContext _Context)
  21. {
  22. context = _Context;
  23. dbSet = context.Set<T>();
  24. }
  25. public async Task<T> AddAsync(T entity)
  26. {
  27. await dbSet.AddAsync(entity);
  28. return entity;
  29. }
  30. public async Task DeleteAsync(T entity)
  31. {
  32. dbSet.Remove(entity);
  33. }
  34. public async Task<IReadOnlyList<T>> GetAllAsync()
  35. {
  36. return await dbSet.ToListAsync();
  37. }
  38. public async Task<T> GetByIdAsync(long id)
  39. {
  40. return await context.Set<T>().FindAsync(id);
  41. }
  42. public IQueryable<T> AsQueryable()
  43. {
  44. return dbSet.AsQueryable<T>();
  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. }
  70. }