You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
64 lines
2.3 KiB
64 lines
2.3 KiB
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<Stock> Stocks { get; set; }
|
|
public DbSet<StockChangeLog> StockChangeLogs { get; set; }
|
|
public DbSet<StockLog> 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();
|
|
}
|
|
}
|
|
}
|
|
|