VEfDbContextBase.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using Microsoft.EntityFrameworkCore;
  2. using System;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. using VCommon.VEntity;
  6. namespace VCommon.VEntityFrameworkCore
  7. {
  8. public abstract class VEfDbContextBase : DbContext
  9. {
  10. protected VEfDbContextBase()
  11. {
  12. }
  13. protected VEfDbContextBase(DbContextOptions options):base(options)
  14. {
  15. }
  16. public override int SaveChanges()
  17. {
  18. foreach (var track in ChangeTracker.Entries<IHaveCreationTime>().Where(p => p.State == EntityState.Added)) track.Entity.CreationTime = DateTime.Now;
  19. foreach (var track in ChangeTracker.Entries<IHaveLastModificationTime>().Where(p => p.State == EntityState.Modified)) track.Entity.LastModificationTime = DateTime.Now;
  20. foreach (var track in ChangeTracker.Entries<ISoftDelete>().Where(p => p.State == EntityState.Deleted))
  21. {
  22. track.State = EntityState.Modified;
  23. track.Entity.IsAbolish = true;
  24. if (track.Entity is IHaveLastModificationTime lmd) lmd.LastModificationTime = DateTime.Now;
  25. }
  26. return base.SaveChanges();
  27. }
  28. }
  29. }