using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using MTWorkHR.Core.Entities.Base; using MTWorkHR.Identity.Entities; namespace MTWorkHR.Identity.DBContext { public class HRIdentityDBContext : IdentityDbContext { // private readonly GlobalInfo _globalInfo; public HRIdentityDBContext(DbContextOptions options/*, GlobalInfo globalInfo*/) : base(options) { // this._globalInfo = globalInfo; } public DbSet Permissions { get; set; } public DbSet RolePermissions { get; set; } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.ApplyConfigurationsFromAssembly(typeof(HRIdentityDBContext).Assembly); } #region SaveChanges public override Task SaveChangesAsync(CancellationToken cancellationToken = default) { BeforeSaveProccess(); return base.SaveChangesAsync(cancellationToken); } public override int SaveChanges() { BeforeSaveProccess(); return base.SaveChanges(); } public override int SaveChanges(bool acceptAllChangesOnSuccess) { BeforeSaveProccess(); return base.SaveChanges(acceptAllChangesOnSuccess); } private void BeforeSaveProccess() { var changes = from e in this.ChangeTracker.Entries() where e.State != EntityState.Unchanged select e; foreach (var change in changes) { if (change.State == EntityState.Added) { //if (change.Entity.GetType() == typeof(IAuditEntityx<>)) if (change.Entity is IAudit) { // ((IAudit)change.Entity).CreateUser = _globalInfo.UserId; ((IAudit)change.Entity).CreateDate = DateTime.Now; } } else if (change.State == EntityState.Modified) { if (change.Entity is IAudit && ((change.Entity is IFullAudit && !((IFullAudit)change.Entity).IsDeleted) || change.Entity is not IFullAudit)) { // ((IAudit)change.Entity).UpdateUser = _globalInfo.UserId; ((IAudit)change.Entity).UpdateDate = DateTime.Now; } if (change.Entity is IFullAudit && ((IFullAudit)change.Entity).IsDeleted) { // ((IFullAudit)change.Entity).DeleteUserId = _globalInfo.UserId; } } else if (change.State == EntityState.Deleted) { } } } #endregion } }