HRDataContext.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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. public DbSet<Company> Companies { get; set; }
  16. protected override void OnModelCreating(ModelBuilder modelBuilder)
  17. {
  18. modelBuilder.ApplyConfigurationsFromAssembly(typeof(HRDataContext).Assembly);
  19. base.OnModelCreating(modelBuilder);
  20. }
  21. public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
  22. {
  23. foreach (var entry in base.ChangeTracker.Entries<AuditEntity>().Where(q=> q.State == EntityState.Added || q.State == EntityState.Modified))
  24. {
  25. entry.Entity.UpdateDate = DateTime.Now;
  26. if(entry.State == EntityState.Added)
  27. {
  28. entry.Entity.CreateDate = DateTime.Now;
  29. }
  30. }
  31. return base.SaveChangesAsync(cancellationToken);
  32. }
  33. }
  34. }