Updates
This commit is contained in:
72
DCGEngine.Database/DCGEDbContext.cs
Normal file
72
DCGEngine.Database/DCGEDbContext.cs
Normal file
@@ -0,0 +1,72 @@
|
||||
using DCGEngine.Database.Configuration;
|
||||
using DCGEngine.Database.Interfaces;
|
||||
using DCGEngine.Database.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace DCGEngine.Database;
|
||||
|
||||
public class DCGEDbContext : DbContext
|
||||
{
|
||||
private readonly DCGEDatabaseConfiguration _configuration;
|
||||
private readonly ILogger _logger;
|
||||
|
||||
public DCGEDbContext(IOptions<DCGEDatabaseConfiguration> configuration, ILogger<DCGEDbContext> logger, DbContextOptions options) : base(options)
|
||||
{
|
||||
_logger = logger;
|
||||
_configuration = configuration.Value;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
|
||||
{
|
||||
foreach (var entityEntry in ChangeTracker.Entries())
|
||||
{
|
||||
if (entityEntry.Entity is ITimeTrackedEntity timeTrackedEntity)
|
||||
{
|
||||
if (entityEntry.State is EntityState.Added && timeTrackedEntity.DateCreated is null)
|
||||
{
|
||||
timeTrackedEntity.DateCreated = DateTime.UtcNow;
|
||||
}
|
||||
if (entityEntry.State is EntityState.Modified or EntityState.Added)
|
||||
{
|
||||
timeTrackedEntity.DateUpdated = DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return await base.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
_configuration.DbSetSearchAssemblies.ForEach(assembly =>
|
||||
{
|
||||
foreach (var typeInfo in assembly.DefinedTypes.Where(type => type.IsAssignableTo(typeof(IDbTrackedEntity))))
|
||||
{
|
||||
modelBuilder.Entity(typeInfo.AsType());
|
||||
}
|
||||
});
|
||||
base.OnModelCreating(modelBuilder);
|
||||
}
|
||||
|
||||
public void UpdateDatabase()
|
||||
{
|
||||
IEnumerable<string> pendingMigrations = Database.GetPendingMigrations();
|
||||
if (!pendingMigrations.Any())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (string migration in pendingMigrations)
|
||||
{
|
||||
_logger.LogInformation("Found pending migration with name {migrationName}.", migration);
|
||||
}
|
||||
_logger.LogInformation("Attempting to apply pending migrations...");
|
||||
Database.Migrate();
|
||||
_logger.LogInformation("Migrations applied.");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user