1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
- using Microsoft.EntityFrameworkCore;
- using MTWorkHR.Core.Entities.Base;
- using MTWorkHR.Core.Global;
- using MTWorkHR.Identity.Entities;
- namespace MTWorkHR.Identity.DBContext
- {
- public class HRIdentityDBContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
- {
- private readonly GlobalInfo _globalInfo;
- public HRIdentityDBContext(DbContextOptions<HRIdentityDBContext> options, GlobalInfo globalInfo) : base(options) {
- this._globalInfo = globalInfo;
- }
- public DbSet<AttachmentType> AttachmentTypes { get; set; }
- public DbSet<UserAttachment> UserAttachments { get; set; }
- public DbSet<Permission> Permissions { get; set; }
- public DbSet<RolePermission> RolePermissions { get; set; }
- protected override void OnModelCreating(ModelBuilder builder)
- {
- base.OnModelCreating(builder);
- builder.ApplyConfigurationsFromAssembly(typeof(HRIdentityDBContext).Assembly);
- }
- #region SaveChanges
- public override Task<int> 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 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
- }
- }
|