#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Models.Common; using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Events; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; #endregion namespace Lumina.DataAccess.Core.UoW; /// /// DbContext for the Lumina application. /// /// To add a new migration: add-migration InitialMigration -p Lumina.DataAccess -s Lumina.Presentation.Api -o Common\Migrations /// To update the database: update-database -p Lumina.DataAccess -s Lumina.Presentation.Api public class LuminaDbContext : DbContext { #region ==================================================================== PROPERTIES ================================================================================= public virtual DbSet Books { get; set; } = null!; #endregion #region ====================================================================== CTOR ===================================================================================== /// /// Initializes a new instance of the class. /// /// The options for configuring the database context. public LuminaDbContext(DbContextOptions options) : base(options) { } #endregion #region ===================================================================== METHODS =================================================================================== /// /// Configures the entity mappings for the database context. /// /// The model builder used to configure the entity mappings. protected override void OnModelCreating(ModelBuilder modelBuilder) { // find all the entity configurations in the assembly and apply them modelBuilder .Ignore>() .ApplyConfigurationsFromAssembly(typeof(LuminaDbContext).Assembly); base.OnModelCreating(modelBuilder); } /// /// Overrides the SaveChanges method of the DbContext class to automatically set the Created and Updated properties of entities that implement the . /// /// The number of objects written to the underlying database. public override int SaveChanges() { // get all the entity entries that are either added or modified var entries = ChangeTracker.Entries() .Where(e => e.Entity is IStorageEntity && (e.State is EntityState.Added or EntityState.Modified)); foreach (var entityEntry in entries) { // if the entity is in Added state, set the Created property to the current date and time if (entityEntry.State == EntityState.Added) ((IStorageEntity)entityEntry.Entity).Created = DateTime.UtcNow; // otherwise, if the entity is in Modified state, set the Updated property to the current date and time else if (entityEntry.State == EntityState.Modified) ((IStorageEntity)entityEntry.Entity).Updated = DateTime.UtcNow; } return base.SaveChanges(); } #endregion }