Repository.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using ConsoleHttp.Model;
  7. using MqttMsgServer.Model;
  8. namespace MqttMsgServer.Dao
  9. {
  10. public class DbRepository<TPrimaryKey, T> : IRepository<TPrimaryKey, T> where T : Entity<TPrimaryKey>
  11. {
  12. private readonly ApplicationDbContext _dbContext;
  13. //public DbRepository(ApplicationDbContext dbContext)
  14. //{
  15. // _dbContext = dbContext;
  16. //}
  17. public DbRepository()
  18. {
  19. _dbContext = new ApplicationDbContext();
  20. }
  21. public IEnumerable<T> GetAll()
  22. {
  23. return _dbContext.Set<T>().Where(i => true);
  24. }
  25. public T GetById(TPrimaryKey id)
  26. {
  27. return _dbContext.Set<T>().AsNoTracking().FirstOrDefault(i => i.Id.Equals(id));
  28. }
  29. public T Add(T t)
  30. {
  31. _dbContext.Set<T>().Add(t);
  32. if (_dbContext.SaveChanges() > 0)
  33. {
  34. return t;
  35. }
  36. return null;
  37. }
  38. public T Update(T t)
  39. {
  40. _dbContext.Set<T>().Attach(t);
  41. if (_dbContext.SaveChanges() > 0)
  42. {
  43. return t;
  44. }
  45. return null;
  46. }
  47. public T Delete(T t)
  48. {
  49. _dbContext.Set<T>().Remove(t);
  50. if (_dbContext.SaveChanges() > 0)
  51. {
  52. return t;
  53. }
  54. return null;
  55. }
  56. }
  57. }