HRDataContext.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. public DbSet<Project> Projects { get; set; }
  17. // public DbSet<AttachmentType> AttachmentTypes { get; set; }
  18. public DbSet<UserTaskStatus> UserTaskStatuses { get; set; }
  19. public DbSet<UserTaskAttachment> UserTaskAttachments { get; set; }
  20. public DbSet<UserTask> UserTasks { get; set; }
  21. public DbSet<UserTaskHistory> UserTaskHistories { get; set; }
  22. //------------------------Logs------------------------
  23. public DbSet<UserLog> UserLogs { get; set; }
  24. public DbSet<AuthLog> AuthLogs { get; set; }
  25. public DbSet<FileLog> FileLogs { get; set; }
  26. public DbSet<RoleLog> RoleLogs { get; set; }
  27. public DbSet<SettingLog> SettingLogs { get; set; }
  28. protected override void OnModelCreating(ModelBuilder modelBuilder)
  29. {
  30. base.OnModelCreating(modelBuilder);
  31. SetGlobalFilters(modelBuilder);
  32. modelBuilder.ApplyConfigurationsFromAssembly(typeof(HRDataContext).Assembly);
  33. }
  34. public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
  35. {
  36. foreach (var entry in base.ChangeTracker.Entries<AuditEntity>().Where(q=> q.State == EntityState.Added || q.State == EntityState.Modified))
  37. {
  38. entry.Entity.UpdateDate = DateTime.Now;
  39. if(entry.State == EntityState.Added)
  40. {
  41. entry.Entity.CreateDate = DateTime.Now;
  42. }
  43. }
  44. return base.SaveChangesAsync(cancellationToken);
  45. }
  46. private void SetGlobalFilters(ModelBuilder builder)
  47. {
  48. builder.SetQueryFilterOnAllEntities<ISoftDelete>(p => !p.IsDeleted);
  49. }
  50. }
  51. }