Repository.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using Azure;
  2. using Microsoft.EntityFrameworkCore;
  3. using MTWorkHR.Core.Entities.Base;
  4. using MTWorkHR.Core.IRepositories.Base;
  5. using MTWorkHR.Infrastructure.Data;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. namespace MTWorkHR.Infrastructure.Repositories
  12. {
  13. public class Repository<T> : IRepository<T> where T : Entity
  14. {
  15. protected readonly HRDataContext _context;
  16. private readonly DbSet<T> dbSet;
  17. public Repository(HRDataContext context)
  18. {
  19. _context = context;
  20. dbSet = context.Set<T>();
  21. }
  22. public async Task<T> AddAsync(T entity)
  23. {
  24. await _context.AddAsync(entity);
  25. await _context.SaveChangesAsync();
  26. return entity;
  27. }
  28. public async Task<IList<T>> AddRangeAsync(IList<T> entities)
  29. {
  30. await dbSet.AddRangeAsync(entities);
  31. return entities;
  32. }
  33. public async Task DeleteAsync(T entity)
  34. {
  35. dbSet.Remove(entity);
  36. }
  37. public async Task DeleteRangeAsync(IEnumerable<T> entities)
  38. {
  39. dbSet.RemoveRange(entities);
  40. }
  41. public async Task<Tuple<ICollection<T>, int>> GetAllAsync()
  42. {
  43. var query = dbSet.AsQueryable();
  44. var total = await query.CountAsync();
  45. return new Tuple<ICollection<T>, int>(await query.ToListAsync(), total);
  46. }
  47. public async Task<T> GetByIdAsync(long id)
  48. {
  49. return await _context.Set<T>().FindAsync(id);
  50. }
  51. }
  52. }