UnitOfWork.cs 1.9 KB

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