HRIdentityDBContext.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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<Permission> Permissions { get; set; }
  14. public DbSet<RolePermission> RolePermissions { get; set; }
  15. protected override void OnModelCreating(ModelBuilder builder)
  16. {
  17. base.OnModelCreating(builder);
  18. builder.ApplyConfigurationsFromAssembly(typeof(HRIdentityDBContext).Assembly);
  19. }
  20. #region SaveChanges
  21. public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
  22. {
  23. BeforeSaveProccess();
  24. return base.SaveChangesAsync(cancellationToken);
  25. }
  26. public override int SaveChanges()
  27. {
  28. BeforeSaveProccess();
  29. return base.SaveChanges();
  30. }
  31. public override int SaveChanges(bool acceptAllChangesOnSuccess)
  32. {
  33. BeforeSaveProccess();
  34. return base.SaveChanges(acceptAllChangesOnSuccess);
  35. }
  36. private void BeforeSaveProccess()
  37. {
  38. var changes = from e in this.ChangeTracker.Entries()
  39. where e.State != EntityState.Unchanged
  40. select e;
  41. foreach (var change in changes)
  42. {
  43. if (change.State == EntityState.Added)
  44. {
  45. //if (change.Entity.GetType() == typeof(IAuditEntityx<>))
  46. if (change.Entity is IAudit)
  47. {
  48. // ((IAudit)change.Entity).CreateUser = _globalInfo.UserId;
  49. ((IAudit)change.Entity).CreateDate = DateTime.Now;
  50. }
  51. }
  52. else if (change.State == EntityState.Modified)
  53. {
  54. if (change.Entity is IAudit
  55. && ((change.Entity is IFullAudit && !((IFullAudit)change.Entity).IsDeleted) || change.Entity is not IFullAudit))
  56. {
  57. // ((IAudit)change.Entity).UpdateUser = _globalInfo.UserId;
  58. ((IAudit)change.Entity).UpdateDate = DateTime.Now;
  59. }
  60. if (change.Entity is IFullAudit && ((IFullAudit)change.Entity).IsDeleted)
  61. {
  62. // ((IFullAudit)change.Entity).DeleteUserId = _globalInfo.UserId;
  63. }
  64. }
  65. else if (change.State == EntityState.Deleted)
  66. {
  67. }
  68. }
  69. }
  70. #endregion
  71. }
  72. }