123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- using ERP.Core.Entity;
- 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);
- }
- /// <summary>
- /// 配置模型关系
- /// </summary>
- /// <param name="modelBuilder"></param>
- protected override void OnModelCreating(ModelBuilder modelBuilder)
- {
- modelBuilder.Entity<SysUserRole>().HasNoKey();
- modelBuilder.Entity<SysRoleMenu>().HasNoKey();
- var assembly = Assembly.GetExecutingAssembly();
- // 处理配置项
- modelBuilder.ApplyConfigurationsFromAssembly(assembly);
- foreach (Type type in assembly.ExportedTypes
- .Where(t => t.IsClass && (t.BaseType == typeof(BaseEntity) || t.BaseType == typeof(TreeEntity))))
- {
- 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();
- }));
- }
- }
- }
|