HRIdentityDBContext.cs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
  2. using Microsoft.EntityFrameworkCore;
  3. using MTWorkHR.Core.Entities.Base;
  4. using MTWorkHR.Identity.Entities;
  5. namespace MTWorkHR.Identity.DBContext
  6. {
  7. public class HRIdentityDBContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
  8. {
  9. // private readonly GlobalInfo _globalInfo;
  10. public HRIdentityDBContext(DbContextOptions<HRIdentityDBContext> options/*, GlobalInfo globalInfo*/) : base(options) {
  11. // this._globalInfo = globalInfo;
  12. }
  13. public DbSet<AttachmentType> AttachmentTypes { get; set; }
  14. public DbSet<UserAttachment> UserAttachments { get; set; }
  15. public DbSet<Permission> Permissions { get; set; }
  16. public DbSet<RolePermission> RolePermissions { get; set; }
  17. protected override void OnModelCreating(ModelBuilder builder)
  18. {
  19. base.OnModelCreating(builder);
  20. builder.ApplyConfigurationsFromAssembly(typeof(HRIdentityDBContext).Assembly);
  21. }
  22. #region SaveChanges
  23. public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
  24. {
  25. BeforeSaveProccess();
  26. return base.SaveChangesAsync(cancellationToken);
  27. }
  28. public override int SaveChanges()
  29. {
  30. BeforeSaveProccess();
  31. return base.SaveChanges();
  32. }
  33. public override int SaveChanges(bool acceptAllChangesOnSuccess)
  34. {
  35. BeforeSaveProccess();
  36. return base.SaveChanges(acceptAllChangesOnSuccess);
  37. }
  38. private void BeforeSaveProccess()
  39. {
  40. var changes = from e in this.ChangeTracker.Entries()
  41. where e.State != EntityState.Unchanged
  42. select e;
  43. foreach (var change in changes)
  44. {
  45. if (change.State == EntityState.Added)
  46. {
  47. //if (change.Entity.GetType() == typeof(IAuditEntityx<>))
  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. }