This repository has been archived on 2023-02-13. You can view files and clone it, but cannot push or open issues or pull requests.
gswi-server/gswi.Data/DatabaseContext.cs

74 lines
2.6 KiB
C#
Raw Permalink Normal View History

2022-02-20 19:04:11 +01:00
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using gswi.Interface.Repositories;
using gswi.Model;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace gswi.Data
{
public class DatabaseContext : DbContext, IUnitOfWork
{
public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options) { }
public DbSet<AuthUser> AuthUsers { get; set; }
public Task<int> SaveChangesAsync()
{
var changedList = ChangeTracker.Entries<IAutoGenerateDateFields>().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<IAutoGenerateDateFields>().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<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
// Datum der letzten Änderung, etc. setzen
DateTimeOffset now = DateTimeOffset.UtcNow;
var changedList = ChangeTracker.Entries<IAutoGenerateDateFields>().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<AuthUser>()
.HasIndex(au => au.EMail)
.IsUnique(true);
modelBuilder.Entity<AuthUser>()
.HasIndex(au => au.ConfirmationId)
.IsUnique(true);
modelBuilder.Entity<AuthUser>()
.HasIndex(au => au.ForgotPasswordId)
.IsUnique(true);
}
}
}