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.
iot/projects/Infrastructure/Data/EfDbContext.cs

95 lines
3.7 KiB

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 MyLoggerFactory = LoggerFactory.Create(builder =>
{
builder.AddConsole();
});
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)
{
optionsBuilder?.UseLoggerFactory(MyLoggerFactory);
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<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();
}
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:<3A>dz<EFBFBD><C7B3><EFBFBD><EFBFBD>ֶ<EFBFBD>Ӧ<EFBFBD><D3A6><EFBFBD><EFBFBD><EFBFBD>ɼ<EFBFBD>", Justification = "<<3C><><EFBFBD><EFBFBD>>")]
public static Action<ModelBuilder> OnModelCreatingAction;
}
}