AbstractRepository.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System.Linq.Expressions;
  2. using DataLayer.Interfaces;
  3. using Domain;
  4. using Microsoft.EntityFrameworkCore;
  5. namespace DataLayer;
  6. public class AbstractRepository<T> : IAbstractRepository<T> where T : BaseEntity
  7. {
  8. #region Fields
  9. private readonly DeathwatchDbContext _deathwatchDbContext;
  10. private readonly DbSet<T> _entities;
  11. #endregion
  12. public AbstractRepository(DeathwatchDbContext deathwatchDbContext)
  13. {
  14. _deathwatchDbContext = deathwatchDbContext;
  15. _entities = _deathwatchDbContext.Set<T>();
  16. }
  17. #region Public Methods
  18. public async Task<T> GetById(int id)
  19. {
  20. return await _entities.FindAsync(id);
  21. }
  22. public async Task<T> FirstOrDefault(Expression<Func<T, bool>> predicate)
  23. {
  24. var entity = await _entities.FirstOrDefaultAsync(predicate);
  25. return entity;
  26. }
  27. public async Task Add(T entity)
  28. {
  29. await _entities.AddAsync(entity);
  30. await _deathwatchDbContext.SaveChangesAsync();
  31. }
  32. public Task Update(T entity)
  33. {
  34. // In case AsNoTracking is used
  35. _deathwatchDbContext.Entry(entity).State = EntityState.Modified;
  36. return _deathwatchDbContext.SaveChangesAsync();
  37. }
  38. public Task Remove(T entity)
  39. {
  40. _entities.Remove(entity);
  41. return _deathwatchDbContext.SaveChangesAsync();
  42. }
  43. public async Task<IEnumerable<T>> GetAll()
  44. {
  45. var entries = await _entities.ToListAsync();
  46. return entries;
  47. }
  48. public async Task<IEnumerable<T>> GetWhere(Expression<Func<T, bool>> predicate)
  49. {
  50. return await _entities.Where(predicate).ToListAsync();
  51. }
  52. public Task<int> CountAll()
  53. {
  54. return _entities.CountAsync();
  55. }
  56. public Task<int> CountWhere(Expression<Func<T, bool>> predicate)
  57. {
  58. return _entities.CountAsync(predicate);
  59. }
  60. #endregion
  61. }