You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

82 lines
1.8 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Core.Db;
  7. using Domain;
  8. using Microsoft.EntityFrameworkCore;
  9. using Microsoft.Extensions.DependencyInjection;
  10. namespace Services
  11. {
  12. public class BaseService<T> : IBaseService<T>
  13. where T:BaseEntity
  14. {
  15. public readonly PanakDbContext _db;
  16. public BaseService(IServiceProvider serviceProvider)
  17. {
  18. _db = serviceProvider.GetService<PanakDbContext>();
  19. }
  20. public virtual void Add(T entity)
  21. {
  22. _db.Add(entity);
  23. _db.SaveChanges();
  24. }
  25. public virtual void Update(T entity)
  26. {
  27. entity.ModifyDate=DateTime.Now;
  28. _db.SaveChanges();
  29. }
  30. public virtual void Delete(Guid id)
  31. {
  32. DeleteWithoutSave(id);
  33. _db.SaveChanges();
  34. }
  35. public virtual void DeleteWithoutSave(Guid id)
  36. {
  37. var item = GetById(id);
  38. _db.Remove(item);
  39. }
  40. public virtual void SaveChanges()
  41. {
  42. _db.SaveChanges();
  43. }
  44. public virtual IQueryable<T> GetQueryable()
  45. {
  46. return _db.Set<T>().AsQueryable();
  47. }
  48. public virtual IQueryable<T> GetWithPaging(int page = 1, int pageSize = 100)
  49. {
  50. return GetQueryable().Skip(Math.Max(0, (page - 1) * pageSize)).Take(pageSize);
  51. }
  52. public virtual T GetById(Guid id)
  53. {
  54. return _db.Set<T>().FirstOrDefault(x=>x.Id==id);
  55. }
  56. public virtual void AddOrUpdate(T entity)
  57. {
  58. if(entity.Id!=Guid.Empty)
  59. Update(entity);
  60. else
  61. Add(entity);
  62. }
  63. public virtual bool CanBeDeleted(Guid id)
  64. {
  65. return true;
  66. }
  67. }
  68. }