using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using app.Interface.Repositories; using app.Model; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace app.Data { public class DatabaseContext : DbContext, IUnitOfWork { public DatabaseContext(DbContextOptions options) : base(options) { } public DbSet AuthUsers { get; set; } public Task SaveChangesAsync() { var changedList = ChangeTracker.Entries().Where(x => x.State == EntityState.Added || x.State == EntityState.Modified); foreach (var item in changedList) { item.Entity.LastModifiedOn = DateTime.UtcNow; if (item.State == EntityState.Added) item.Entity.CreatedOn = DateTime.UtcNow; } return base.SaveChangesAsync(); } public override int SaveChanges() { var changedList = ChangeTracker.Entries().Where(x => x.State == EntityState.Added || x.State == EntityState.Modified); foreach (var item in changedList) { item.Entity.LastModifiedOn = DateTime.UtcNow; if (item.State == EntityState.Added) item.Entity.CreatedOn = DateTime.UtcNow; } return base.SaveChanges(); } public override Task SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken)) { // Datum der letzten Änderung, etc. setzen DateTimeOffset now = DateTimeOffset.UtcNow; var changedList = ChangeTracker.Entries().Where(x => x.State == EntityState.Added || x.State == EntityState.Modified); foreach (var item in changedList) { item.Entity.LastModifiedOn = now; if (item.State == EntityState.Added) item.Entity.CreatedOn = now; } return base.SaveChangesAsync(); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity() .HasIndex(au => au.EMail) .IsUnique(true); modelBuilder.Entity() .HasIndex(au => au.ConfirmationId) .IsUnique(true); modelBuilder.Entity() .HasIndex(au => au.ForgotPasswordId) .IsUnique(true); } } }