[CHANGE] Reworked db with interceptors
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
using Manager.Data.Entities;
|
||||
using Manager.Data.Entities.Audit;
|
||||
using Manager.Data.Entities.LibraryContext;
|
||||
using Manager.Data.Entities.LibraryContext.Join;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -13,6 +13,8 @@ public sealed class LibraryDbContext : DbContext
|
||||
ChangeTracker.LazyLoadingEnabled = false;
|
||||
Database.EnsureCreated();
|
||||
}
|
||||
|
||||
public DbSet<EntityHistory> Histories { get; set; }
|
||||
|
||||
public DbSet<CaptionEntity> Captions { get; set; }
|
||||
public DbSet<ChannelEntity> Channels { get; set; }
|
||||
@@ -21,9 +23,20 @@ public sealed class LibraryDbContext : DbContext
|
||||
public DbSet<MediaEntity> Media { get; set; }
|
||||
public DbSet<MediaFormatEntity> MediaFormats { get; set; }
|
||||
public DbSet<PlaylistEntity> Playlists { get; set; }
|
||||
// Other media (images)?
|
||||
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
optionsBuilder.AddInterceptors(new DateInterceptor(), new AuditInterceptor());
|
||||
}
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<EntityHistory>(eh =>
|
||||
{
|
||||
eh.ToTable("entity_history");
|
||||
});
|
||||
|
||||
modelBuilder.Entity<CaptionEntity>(ce =>
|
||||
{
|
||||
ce.ToTable("captions");
|
||||
@@ -101,31 +114,4 @@ public sealed class LibraryDbContext : DbContext
|
||||
|
||||
base.OnModelCreating(modelBuilder);
|
||||
}
|
||||
|
||||
public override int SaveChanges()
|
||||
{
|
||||
UpdateEntryDates();
|
||||
return base.SaveChanges();
|
||||
}
|
||||
|
||||
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new())
|
||||
{
|
||||
UpdateEntryDates();
|
||||
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
|
||||
}
|
||||
|
||||
private void UpdateEntryDates()
|
||||
{
|
||||
var entries = ChangeTracker.Entries().Where(x => x is { Entity: DateTimeBase, State: EntityState.Added or EntityState.Modified });
|
||||
|
||||
foreach (var entity in entries)
|
||||
{
|
||||
((DateTimeBase)entity.Entity).LastModifiedUtc = DateTime.UtcNow;
|
||||
|
||||
if (entity.State == EntityState.Added)
|
||||
{
|
||||
((DateTimeBase)entity.Entity).CreatedAtUtc = DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user