using EF_ChangeLog.Model; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EF_ChangeLog.Controller { internal class StockDbContext : DbContext { public DbSet Stocks { get; set; } public DbSet StockChangeLogs { get; set; } public DbSet stockLogs { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"Data Source=peacecloud.synology.me,21433;Initial Catalog=Study;User ID=study;Password=Study1234;Encrypt=false"); base.OnConfiguring(optionsBuilder); } public override int SaveChanges() { var modifiedEntities = ChangeTracker.Entries().ToList(); for (var i = 0; i < modifiedEntities.Count; i++) { var entry = modifiedEntities[i]; var entitiy = entry.Entity; if (entitiy.GetType() != typeof(Stock)) continue; if (entitiy is Stock stock && entry.State != EntityState.Added) { StockLog stockLog = new StockLog() { OriginalId = (int)entry.OriginalValues[nameof(Stock.Id)], Name = (string)entry.OriginalValues[nameof(Stock.Name)], Price = (decimal)entry.OriginalValues[nameof(Stock.Price)], LoggedAt = DateTime.Now }; this.stockLogs.Add(stockLog); } var changeLog = new StockChangeLog() { EntityName = entitiy.GetType().Name, EntityId = (int)entitiy.GetType().GetProperty("Id").GetValue(entitiy), ChangeBy = "User", ChangeDate = DateTime.Now, ActionType = entry.State.ToString(), OriginalSnapshot = (string)entitiy.GetType().GetProperty("OriginalSnapshot").GetValue(entitiy) }; StockChangeLogs.Add(changeLog); } return base.SaveChanges(); } } }