using ERP.Core.Entities; using ERP.Framework.WebApi; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Serilog; using System.Reflection; namespace ERP.Core { public class CoreDbContext : DbContext { private readonly IConfiguration _configuration; public CoreDbContext(IConfiguration configuration) { _configuration = configuration; } public override int SaveChanges() { BeforeSaveChanges(); var result = base.SaveChanges(); AfterSaveChanges(); return result; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { var name = GetType().Name; // 可扩展为多租户,从当前请求头拿租户Id,根据租户Id获取对应数据库配置名,替换 string connect = _configuration.GetConnectionString(name)!; // 可扩展为使用多种数据库,添加配置项数组根据不同租户Id,配置不同库类型,Key为租户Id/库名,对象包含数据库类型等 optionsBuilder.UseMySql(connect, new MySqlServerVersion(new Version(8, 0, 26))); UseLog(optionsBuilder); base.OnConfiguring(optionsBuilder); } /// /// 配置模型关系 /// /// protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().HasNoKey(); modelBuilder.Entity().HasNoKey(); var assembly = Assembly.GetExecutingAssembly(); // 处理配置项 modelBuilder.ApplyConfigurationsFromAssembly(assembly); foreach (Type type in assembly.ExportedTypes .Where(t => t.IsClass && IsBaseEntityDerived(t))) { modelBuilder.Model.AddEntityType(type); } } private void BeforeSaveChanges() { ChangeTracker.DetectChanges(); var entityEntries = ChangeTracker.Entries().ToList(); foreach (var entry in entityEntries) { // 新增时赋值CreatetIime CreateBy if (entry.State == EntityState.Added) { Entry(entry.Entity).Property(nameof(BaseEntity.CreateTime)).CurrentValue = DateTime.Now; //Entry(entry.Entity).Property(nameof(BaseEntity.CreateBy)).CurrentValue = DateTime.Now; } if (entry.State == EntityState.Deleted) { } // 修改时赋值CreatetIime CreateBy if (entry.State == EntityState.Modified) { Entry(entry.Entity).Property(nameof(BaseEntity.UpdateTime)).CurrentValue = DateTime.Now; } } } private void AfterSaveChanges() { } private void UseLog(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseLoggerFactory(LoggerFactory.Create(builder => { builder.AddConsole(); builder.AddSerilog(); })); } public static void RegisterEntities(Assembly assembly, ModelBuilder modelBuilder) { foreach (Type type in assembly.ExportedTypes) { if (type.IsClass && IsBaseEntityDerived(type)) { modelBuilder.Model.AddEntityType(type); } } } private static bool IsBaseEntityDerived(Type type) { // 检查类型是否是BaseEntity或其派生类 return type.BaseType == typeof(BaseEntity) || IsDerivedFromGenericBase(type, typeof(TreeEntity<>)); } private static bool IsDerivedFromGenericBase(Type type, Type genericBaseType) { // 检查类型是否是泛型基类的派生类 if (type.IsGenericType && type.GetGenericTypeDefinition() == genericBaseType) { return true; } // 递归检查基类 if (type.BaseType != null && IsDerivedFromGenericBase(type.BaseType, genericBaseType)) { return true; } return false; } } }