UnitOfWork.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System.Reflection;
  2. using MTWorkHR.Core.UnitOfWork;
  3. using MTWorkHR.Infrastructure.Data;
  4. using MTWorkHR.Core.IRepositories;
  5. using MTWorkHR.Core.Global;
  6. namespace MTWorkHR.Infrastructure.UnitOfWorks
  7. {
  8. public class UnitOfWork : IUnitOfWork
  9. {
  10. private readonly HRDataContext context;
  11. public IPermissionRepository Permission { get; }
  12. public UnitOfWork(HRDataContext _context
  13. , IPermissionRepository Permission
  14. )
  15. {
  16. context = _context;
  17. this.Permission = Permission;
  18. }
  19. public async Task<int> CompleteAsync()
  20. {
  21. try
  22. {
  23. return await context.SaveChangesAsync();
  24. }
  25. catch (Exception ex)
  26. {
  27. RollbackTran();
  28. throw ex;
  29. }
  30. }
  31. public object GetRepositoryByName(string name)
  32. {
  33. Type type = this.GetType();
  34. PropertyInfo info = type.GetProperty(name);
  35. if (info == null)
  36. throw new AppException(ExceptionEnum.PropertyNotAccess, name, type.FullName);
  37. //type.FullName, String.Format("A property called {0} can't be accessed for type {1}.", name));
  38. return info.GetValue(this, null);
  39. }
  40. public void BeginTran()
  41. {
  42. context.Database.BeginTransaction();
  43. }
  44. public void CommitTran()
  45. {
  46. context.Database.CommitTransaction();
  47. }
  48. public void RollbackTran()
  49. {
  50. var transaction = context.Database.CurrentTransaction;
  51. if (transaction != null)
  52. context.Database.RollbackTransaction();
  53. }
  54. }
  55. }