HRIdentityDBContext.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
  2. using Microsoft.EntityFrameworkCore;
  3. using MTWorkHR.Core.Entities.Base;
  4. using MTWorkHR.Core.Global;
  5. using MTWorkHR.Identity.Entities;
  6. namespace MTWorkHR.Identity.DBContext
  7. {
  8. public class HRIdentityDBContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
  9. {
  10. private readonly GlobalInfo _globalInfo;
  11. public HRIdentityDBContext(DbContextOptions<HRIdentityDBContext> options, GlobalInfo globalInfo) : base(options) {
  12. this._globalInfo = globalInfo;
  13. }
  14. public DbSet<AttachmentType> AttachmentTypes { get; set; }
  15. public DbSet<UserAttachment> UserAttachments { get; set; }
  16. public DbSet<Permission> Permissions { get; set; }
  17. public DbSet<RolePermission> RolePermissions { get; set; }
  18. protected override void OnModelCreating(ModelBuilder builder)
  19. {
  20. base.OnModelCreating(builder);
  21. builder.ApplyConfigurationsFromAssembly(typeof(HRIdentityDBContext).Assembly);
  22. }
  23. #region SaveChanges
  24. public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
  25. {
  26. BeforeSaveProccess();
  27. return base.SaveChangesAsync(cancellationToken);
  28. }
  29. public override int SaveChanges()
  30. {
  31. BeforeSaveProccess();
  32. return base.SaveChanges();
  33. }
  34. public override int SaveChanges(bool acceptAllChangesOnSuccess)
  35. {
  36. BeforeSaveProccess();
  37. return base.SaveChanges(acceptAllChangesOnSuccess);
  38. }
  39. private void BeforeSaveProccess()
  40. {
  41. var changes = from e in this.ChangeTracker.Entries()
  42. where e.State != EntityState.Unchanged
  43. select e;
  44. foreach (var change in changes)
  45. {
  46. if (change.State == EntityState.Added)
  47. {
  48. if (change.Entity is IAudit)
  49. {
  50. ((IAudit)change.Entity).CreateUser = _globalInfo.UserId;
  51. ((IAudit)change.Entity).CreateDate = DateTime.Now;
  52. }
  53. }
  54. else if (change.State == EntityState.Modified)
  55. {
  56. if (change.Entity is IAudit
  57. && ((change.Entity is IFullAudit && !((IFullAudit)change.Entity).IsDeleted) || change.Entity is not IFullAudit))
  58. {
  59. ((IAudit)change.Entity).UpdateUser = _globalInfo.UserId;
  60. ((IAudit)change.Entity).UpdateDate = DateTime.Now;
  61. }
  62. if (change.Entity is IFullAudit && ((IFullAudit)change.Entity).IsDeleted)
  63. {
  64. ((IFullAudit)change.Entity).DeleteUserId = _globalInfo.UserId;
  65. }
  66. }
  67. else if (change.State == EntityState.Deleted)
  68. {
  69. }
  70. }
  71. }
  72. #endregion
  73. }
  74. }