HRDataContext.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. using Microsoft.EntityFrameworkCore;
  2. using MTWorkHR.Core.Entities;
  3. using MTWorkHR.Core.Entities.Base;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Data;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace MTWorkHR.Infrastructure.Data
  11. {
  12. public class HRDataContext : DbContext
  13. {
  14. public HRDataContext(DbContextOptions<HRDataContext> options) : base(options) { }
  15. protected override void OnModelCreating(ModelBuilder modelBuilder)
  16. {
  17. modelBuilder.ApplyConfigurationsFromAssembly(typeof(HRDataContext).Assembly);
  18. base.OnModelCreating(modelBuilder);
  19. }
  20. public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
  21. {
  22. foreach (var entry in base.ChangeTracker.Entries<AuditEntity>().Where(q=> q.State == EntityState.Added || q.State == EntityState.Modified))
  23. {
  24. entry.Entity.UpdateDate = DateTime.Now;
  25. if(entry.State == EntityState.Added)
  26. {
  27. entry.Entity.CreateDate = DateTime.Now;
  28. }
  29. }
  30. return base.SaveChangesAsync(cancellationToken);
  31. }
  32. }
  33. }