AbstractRepository.cs 2.2 KB

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