UnitOfWork.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 IUserTaskRepository UserTask { get; }
  17. public ITaskStatusRepository UserTaskStatus { get; }
  18. public IUserTaskHistoryRepository UserTaskHistory { get; }
  19. public IUserTaskAttachmentRepository UserTaskAttachment { get; }
  20. public IProjectRepository Project { get; }
  21. public UnitOfWork(HRDataContext _context
  22. , IPermissionRepository permission
  23. , ICompanyRepository company
  24. , IUserTaskRepository userTask
  25. , IProjectRepository project
  26. , IUserTaskHistoryRepository projectHistory
  27. , ITaskStatusRepository userTaskStatus
  28. // ,IUserTaskAttachmentRepository userTaskAttachment
  29. )
  30. {
  31. context = _context;
  32. this.Permission = permission;
  33. this.Company = company;
  34. this.UserTask = userTask;
  35. this.Project = project;
  36. this.UserTaskHistory = projectHistory;
  37. this.UserTaskStatus = userTaskStatus;
  38. // this.UserTaskAttachment = userTaskAttachment;
  39. }
  40. public async Task<int> CompleteAsync()
  41. {
  42. try
  43. {
  44. return await context.SaveChangesAsync();
  45. }
  46. catch (Exception ex)
  47. {
  48. RollbackTran();
  49. throw ex;
  50. }
  51. }
  52. public object GetRepositoryByName(string name)
  53. {
  54. Type type = this.GetType();
  55. PropertyInfo info = type.GetProperty(name);
  56. if (info == null)
  57. throw new AppException(ExceptionEnum.PropertyNotAccess, name, type.FullName);
  58. //type.FullName, String.Format("A property called {0} can't be accessed for type {1}.", name));
  59. return info.GetValue(this, null);
  60. }
  61. public void BeginTran()
  62. {
  63. context.Database.BeginTransaction();
  64. }
  65. public void CommitTran()
  66. {
  67. context.Database.CommitTransaction();
  68. }
  69. public void RollbackTran()
  70. {
  71. var transaction = context.Database.CurrentTransaction;
  72. if (transaction != null)
  73. context.Database.RollbackTransaction();
  74. }
  75. }
  76. }