using Infrastructure.Domain; using Infrastructure.Extensions; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace Infrastructure.Data { public class EfDbContext : DbContext { public static readonly ILoggerFactory DebugLogFactory = LoggerFactory.Create(builder => { builder.AddConsole(); }); public static readonly ILoggerFactory ProductLogFactory = LoggerFactory.Create(builder => { }); private readonly IHostEnvironment _env; private readonly IConfiguration _cfg; public EfDbContext(DbContextOptions options, IHostEnvironment env, IConfiguration cfg) : base(options) { this._env = env; this._cfg = cfg; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (this._cfg.GetValue("debug", false)) { optionsBuilder?.UseLoggerFactory(DebugLogFactory); } else { optionsBuilder?.UseLoggerFactory(ProductLogFactory); } optionsBuilder?.EnableSensitiveDataLogging(); base.OnConfiguring(optionsBuilder); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.RemovePluralizingTableNameConvention(); OnModelCreatingAction(modelBuilder); foreach (var entity in modelBuilder.Model.GetEntityTypes()) { if (entity.GetProperties().Any(o => o.Name == "Id")) { modelBuilder.Entity(entity.Name).HasKey("Id"); modelBuilder.Entity(entity.Name).Property("Id").ValueGeneratedNever(); } if (entity.GetProperties().Any(o => o.Name == "RowVersion")) { modelBuilder.Entity(entity.Name).Property("RowVersion")?.IsConcurrencyToken().ValueGeneratedNever(); } } } public override int SaveChanges() { this.ChangeTracker.DetectChanges(); var entries = this.ChangeTracker.Entries().Where(o => o.State == EntityState.Added || o.State == EntityState.Modified || o.State == EntityState.Deleted).ToList(); foreach (var entry in entries) { var entity = entry.Entity as BaseEntity; if (entity is IValidatableObject) { var validationResults = new List(); if (!Validator.TryValidateObject(entry.Entity, new ValidationContext(entity, null, null), validationResults, true)) { throw new EntityInvalidException(validationResults, $"{entity.GetType().FullName} valid error"); } } if (entity is IVersionEntity) { (entity as IVersionEntity).RowVersion = Guid.NewGuid().ToString(); } Console.WriteLine($"{entity.GetType().Name}:{entry.State.ToString()}:{entry.OriginalValues.ToObject().ToJson()}/{entry.CurrentValues.ToObject().ToJson()}"); } try { return base.SaveChanges(); } catch (Exception ex) { ex.PrintStack(ex.Message); var list = entries.Select(o => o.Entity).ToList(); Console.WriteLine(list.ToJson()); throw new Exception(ex.Message, ex); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA2211:非常量字段应当不可见", Justification = "<挂起>")] public static Action OnModelCreatingAction; } }