|
|
using Infrastructure.Domain;
|
|
|
using Infrastructure.Events;
|
|
|
using Infrastructure.Extensions;
|
|
|
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.Diagnostics;
|
|
|
using System.Linq;
|
|
|
|
|
|
namespace Infrastructure.Data
|
|
|
{
|
|
|
public class EfDbContext : DbContext
|
|
|
{
|
|
|
public static readonly ILoggerFactory MyLoggerFactory = LoggerFactory.Create(builder =>
|
|
|
{
|
|
|
builder.AddDebug();
|
|
|
});
|
|
|
|
|
|
private readonly ILogger<EfDbContext> _logger;
|
|
|
private readonly IHostEnvironment _env;
|
|
|
private readonly IConfiguration _cfg;
|
|
|
private readonly IDbConfig _dbConfig;
|
|
|
private readonly IEventPublisher _publisher;
|
|
|
|
|
|
public EfDbContext(DbContextOptions options, ILogger<EfDbContext> logger, IHostEnvironment env, IConfiguration cfg, IDbConfig dbConfig, IEventPublisher publisher) : base(options)
|
|
|
{
|
|
|
this._logger = logger;
|
|
|
this._env = env;
|
|
|
this._cfg = cfg;
|
|
|
this._dbConfig = dbConfig;
|
|
|
this._publisher = publisher;
|
|
|
}
|
|
|
|
|
|
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
|
|
{
|
|
|
optionsBuilder?.UseLoggerFactory(MyLoggerFactory);
|
|
|
optionsBuilder?.EnableSensitiveDataLogging();
|
|
|
this._dbConfig.OnConfiguring(optionsBuilder);
|
|
|
}
|
|
|
|
|
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
|
|
{
|
|
|
if (modelBuilder is null)
|
|
|
{
|
|
|
throw new ArgumentNullException(nameof(modelBuilder));
|
|
|
}
|
|
|
this._dbConfig.OnModelCreating(modelBuilder);
|
|
|
var entityTypes = modelBuilder.Model.GetEntityTypes().ToList();
|
|
|
var tablePrefix = this._cfg["tableprefix"];
|
|
|
foreach (var entity in entityTypes)
|
|
|
{
|
|
|
if (!string.IsNullOrEmpty(tablePrefix))
|
|
|
{
|
|
|
entity.SetTableName($"{this._cfg["tableprefix"]}_{entity.GetTableName()}");
|
|
|
}
|
|
|
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();
|
|
|
var events = new List<object>();
|
|
|
foreach (var entry in entries)
|
|
|
{
|
|
|
var entity = entry.Entity as BaseEntity;
|
|
|
if (entity is IValidatableObject)
|
|
|
{
|
|
|
var validationResults = new List<ValidationResult>();
|
|
|
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();
|
|
|
}
|
|
|
if (entry.State == EntityState.Added)
|
|
|
{
|
|
|
events.Add(Activator.CreateInstance(typeof(EntityInsertedEvent<>).MakeGenericType(entry.Entity.GetType()), entry.Entity));
|
|
|
}
|
|
|
else if (entry.State == EntityState.Modified)
|
|
|
{
|
|
|
events.Add(Activator.CreateInstance(typeof(EntityUpdatedEvent<>).MakeGenericType(entry.Entity.GetType()), entry.Entity));
|
|
|
}
|
|
|
else if (entry.State == EntityState.Deleted)
|
|
|
{
|
|
|
events.Add(Activator.CreateInstance(typeof(EntityDeletedEvent<>).MakeGenericType(entry.Entity.GetType()), entry.Entity));
|
|
|
}
|
|
|
this._logger.LogDebug($"{nameof(EfDbContext)}>{entity.GetType().Name}:{entry.State}");
|
|
|
}
|
|
|
try
|
|
|
{
|
|
|
var result = base.SaveChanges();
|
|
|
if (events.Count > 0)
|
|
|
{
|
|
|
events.ForEach(o => this._publisher.Publish(o));
|
|
|
}
|
|
|
return result;
|
|
|
}
|
|
|
catch (DbUpdateException ex)
|
|
|
{
|
|
|
ex.PrintStack();
|
|
|
this._logger.LogError(ex.ToString());
|
|
|
throw;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
[System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA2211:<3A>dz<EFBFBD><C7B3><EFBFBD><EFBFBD>ֶ<EFBFBD>Ӧ<EFBFBD><D3A6><EFBFBD><EFBFBD><EFBFBD>ɼ<EFBFBD>", Justification = "<<3C><><EFBFBD><EFBFBD>>")]
|
|
|
public static Action<ModelBuilder> OnModelCreatingAction;
|
|
|
}
|
|
|
} |