持久层重构为独立 MiGu.DB 工程并优化集成

- 新增 MiGu.DB 项目,迁移所有领域实体与枚举,统一模型约定
- 实现 Entity/Repository/UoW/Provider/Exception 等接口与实现
- 支持数据修补机制,完善 Sqlite 初始迁移与数据库管理
- Server 侧移除 EF Core 相关,依赖 MiGu.DB,PlatformPersistence 适配
- 业务服务注入 UoW/Repository,状态字段统一用 enum 及辅助类
- 统一异常处理,Controller 映射 HTTP 状态码
- 配置项与文档补充数据库启动、SchemaMode、迁移说明
- 新增 GlobalUsings.Db.cs、WmsStatusAliases.cs 简化类型引用
- 新增 HttpActorContextMiddleware 支持操作者上下文一致性
- 新增 MiGuDbContextModelSnapshot 追踪数据库结构
- 优化代码结构,解耦领域与持久层,提升扩展性与安全性
This commit is contained in:
2026-07-27 14:26:04 +08:00
parent bdcd88608c
commit 51c3fc1994
57 changed files with 6663 additions and 1396 deletions
@@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore;
using MiGu.DB.Domains.Dashboard;
using MiGu.DB.Domains.SimpleFields;
using MiGu.DB.Domains.Transport;
using MiGu.DB.Domains.Wms;
namespace MiGu.DB.Kernel.Context;
public partial class MiGuDbContext
{
public DbSet<Warehouse> Warehouses => Set<Warehouse>();
public DbSet<WarehouseArea> WarehouseAreas => Set<WarehouseArea>();
public DbSet<Storage> Storages => Set<Storage>();
public DbSet<Container> Containers => Set<Container>();
public DbSet<MaterialType> MaterialTypes => Set<MaterialType>();
public DbSet<Material> Materials => Set<Material>();
public DbSet<ContainerLocation> ContainerLocations => Set<ContainerLocation>();
public DbSet<ContainerMaterial> ContainerMaterials => Set<ContainerMaterial>();
public DbSet<StockEvent> StockEvents => Set<StockEvent>();
public DbSet<ContainerLocationHistory> ContainerLocationHistories => Set<ContainerLocationHistory>();
public DbSet<ContainerMaterialHistory> ContainerMaterialHistories => Set<ContainerMaterialHistory>();
public DbSet<WmsTransportRule> WmsTransportRules => Set<WmsTransportRule>();
public DbSet<WmsTransportTask> WmsTransportTasks => Set<WmsTransportTask>();
public DbSet<WmsTransportReservation> WmsTransportReservations => Set<WmsTransportReservation>();
public DbSet<WmsTransportTaskHistory> WmsTransportTaskHistories => Set<WmsTransportTaskHistory>();
public DbSet<SimpleField> SimpleFields => Set<SimpleField>();
public DbSet<UserDashboardShortcut> UserDashboardShortcuts => Set<UserDashboardShortcut>();
}
+25
View File
@@ -0,0 +1,25 @@
using Microsoft.EntityFrameworkCore;
using MiGu.DB.Abstractions.Modules;
using MiGu.DB.Kernel.Conventions;
namespace MiGu.DB.Kernel.Context;
public partial class MiGuDbContext : DbContext
{
private readonly IEnumerable<IEntityModule> _modules;
public MiGuDbContext(DbContextOptions<MiGuDbContext> options, IEnumerable<IEntityModule>? modules = null)
: base(options)
{
_modules = modules ?? Array.Empty<IEntityModule>();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// 先约定、后 Configuration,让实体级配置覆盖全局 Guid/时间转换(如 SimpleField
ModelConventionExtensions.ApplyMiGuConventions(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(typeof(MiGuDbContext).Assembly);
foreach (var module in _modules)
module.ConfigureModel(modelBuilder);
}
}
+167
View File
@@ -0,0 +1,167 @@
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using MiGu.DB.Abstractions.Entities;
using MiGu.DB.Abstractions.Runtime;
namespace MiGu.DB.Kernel.Conventions;
/// <summary>
/// 全局模型约定:Guid/DateTimeOffset 字符串化、枚举存字符串、软删过滤、Version 并发令牌等。
/// </summary>
public static class ModelConventionExtensions
{
public static void ApplyMiGuConventions(ModelBuilder modelBuilder)
{
// 与历史 Sqlite TEXT 列兼容:Guid / DateTimeOffset 均以字符串落库
var guid = new ValueConverter<Guid, string>(v => v.ToString("D"), v => Guid.Parse(v));
var nullableGuid = new ValueConverter<Guid?, string?>(
v => v.HasValue ? v.Value.ToString("D") : null,
v => string.IsNullOrWhiteSpace(v) ? null : Guid.Parse(v));
var dto = new ValueConverter<DateTimeOffset, string>(
v => v.UtcDateTime.ToString("O"),
v => DateTimeOffset.Parse(v));
var nullableDto = new ValueConverter<DateTimeOffset?, string?>(
v => v.HasValue ? v.Value.UtcDateTime.ToString("O") : null,
v => string.IsNullOrWhiteSpace(v) ? null : DateTimeOffset.Parse(v));
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
var clr = entityType.ClrType;
foreach (var p in clr.GetProperties().Where(p => p.PropertyType == typeof(Guid)))
modelBuilder.Entity(clr).Property(p.Name).HasConversion(guid).HasMaxLength(36);
foreach (var p in clr.GetProperties().Where(p => p.PropertyType == typeof(Guid?)))
modelBuilder.Entity(clr).Property(p.Name).HasConversion(nullableGuid).HasMaxLength(36);
foreach (var p in clr.GetProperties().Where(p => p.PropertyType == typeof(DateTimeOffset)))
modelBuilder.Entity(clr).Property(p.Name).HasConversion(dto).HasMaxLength(40);
foreach (var p in clr.GetProperties().Where(p => p.PropertyType == typeof(DateTimeOffset?)))
modelBuilder.Entity(clr).Property(p.Name).HasConversion(nullableDto).HasMaxLength(40);
// 严格 1:1 字符串转换;旧值兼容靠 IDataMigrator,禁止在 converter 读侧 Normalize
foreach (var p in clr.GetProperties().Where(p => p.PropertyType.IsEnum))
modelBuilder.Entity(clr).Property(p.Name).HasConversion<string>().HasMaxLength(32);
if (typeof(ISoftDeletable).IsAssignableFrom(clr))
{
var method = typeof(ModelConventionExtensions)
.GetMethod(nameof(SetSoftDeleteFilter), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)!
.MakeGenericMethod(clr);
method.Invoke(null, new object[] { modelBuilder });
}
// Version:业务乐观锁(非数据库 rowversion 字节数组)
if (typeof(IVersioned).IsAssignableFrom(clr))
modelBuilder.Entity(clr).Property(nameof(IVersioned.Version)).IsConcurrencyToken();
if (typeof(ILockable).IsAssignableFrom(clr))
modelBuilder.Entity(clr).Property(nameof(ILockable.IsLock)).HasColumnName("IsLock");
if (typeof(IAuditable).IsAssignableFrom(clr))
{
modelBuilder.Entity(clr).Property(nameof(IAuditable.CreatedBy)).HasMaxLength(128);
modelBuilder.Entity(clr).Property(nameof(IAuditable.UpdatedBy)).HasMaxLength(128);
}
if (typeof(ISoftDeletable).IsAssignableFrom(clr))
modelBuilder.Entity(clr).Property(nameof(ISoftDeletable.DeletedBy)).HasMaxLength(128);
if (typeof(IRemarkable).IsAssignableFrom(clr))
modelBuilder.Entity(clr).Property(nameof(IRemarkable.Remark)).HasMaxLength(1000);
if (typeof(IExtendable).IsAssignableFrom(clr))
modelBuilder.Entity(clr).Property(nameof(IExtendable.Extend)).HasColumnType("text");
}
}
private static void SetSoftDeleteFilter<TEntity>(ModelBuilder modelBuilder)
where TEntity : class, ISoftDeletable
=> modelBuilder.Entity<TEntity>().HasQueryFilter(e => !e.IsDeleted);
}
public sealed class ActorContextAccessor : IActorContextAccessor
{
private static readonly AsyncLocal<IActorContext?> CurrentContext = new();
public IActorContext Current
{
get => CurrentContext.Value ?? SystemActorContext.Instance;
set => CurrentContext.Value = value;
}
}
public sealed class SystemActorContext : IActorContext
{
public static readonly SystemActorContext Instance = new();
public string Name => "system";
}
public sealed class AuditSaveChangesInterceptor : SaveChangesInterceptor
{
private readonly IActorContextAccessor _actors;
public AuditSaveChangesInterceptor(IActorContextAccessor actors) => _actors = actors;
public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
{
Stamp(eventData.Context);
return base.SavingChanges(eventData, result);
}
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
{
Stamp(eventData.Context);
return base.SavingChangesAsync(eventData, result, cancellationToken);
}
private void Stamp(DbContext? db)
{
if (db is null) return;
var now = DateTimeOffset.UtcNow;
var actor = _actors.Current.Name;
foreach (var entry in db.ChangeTracker.Entries())
{
if (entry.Entity is IAuditable auditable)
{
if (entry.State == EntityState.Added)
{
if (entry.Entity is IEntity<Guid> { Id: var id } && id == Guid.Empty)
((IEntity<Guid>)entry.Entity).Id = Guid.NewGuid();
auditable.CreatedAt = now;
auditable.UpdatedAt = now;
if (string.IsNullOrWhiteSpace(auditable.CreatedBy)) auditable.CreatedBy = actor;
if (string.IsNullOrWhiteSpace(auditable.UpdatedBy)) auditable.UpdatedBy = actor;
}
else if (entry.State == EntityState.Modified)
{
auditable.UpdatedAt = now;
auditable.UpdatedBy = actor;
}
}
if (entry.Entity is IVersioned versioned)
{
if (entry.State == EntityState.Added)
versioned.Version = Math.Max(1, versioned.Version);
else if (entry.State == EntityState.Modified)
versioned.Version += 1;
}
if (entry.Entity is IExtendable extendable && string.IsNullOrWhiteSpace(extendable.Extend))
extendable.Extend = "{}";
if (entry.Entity is ISoftDeletable soft
&& entry.State == EntityState.Modified
&& entry.Property(nameof(ISoftDeletable.IsDeleted)).IsModified
&& soft.IsDeleted)
{
soft.DeletedAt ??= now;
if (string.IsNullOrWhiteSpace(soft.DeletedBy)) soft.DeletedBy = actor;
}
}
}
}
@@ -0,0 +1,20 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using MiGu.DB.Kernel.Context;
namespace MiGu.DB.Kernel.Design;
/// <summary>
/// design-time 工厂(dotnet ef migrations add)。指定 MigrationsAssembly,与运行时 SqliteProviderSetup 一致。
/// </summary>
public sealed class MiGuDbContextFactory : IDesignTimeDbContextFactory<MiGuDbContext>
{
public MiGuDbContext CreateDbContext(string[] args)
{
var options = new DbContextOptionsBuilder<MiGuDbContext>()
.UseSqlite("Data Source=platform.db", o =>
o.MigrationsAssembly(typeof(MiGuDbContext).Assembly.GetName().Name))
.Options;
return new MiGuDbContext(options);
}
}
+46
View File
@@ -0,0 +1,46 @@
using MiGu.DB.Abstractions.Entities;
namespace MiGu.DB.Kernel.Entities;
public abstract class Entity<TKey> : IEntity<TKey>
{
public TKey Id { get; set; } = default!;
}
public abstract class AuditedEntity : Entity<Guid>, IAuditable
{
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
public string CreatedBy { get; set; } = "";
public string UpdatedBy { get; set; } = "";
}
public abstract class SoftDeletableEntity : AuditedEntity, ISoftDeletable, IVersioned, ILockable
{
public bool IsDeleted { get; set; }
public DateTimeOffset? DeletedAt { get; set; }
public string DeletedBy { get; set; } = "";
public long Version { get; set; }
public bool IsLock { get; set; }
}
public abstract class AggregateRoot : SoftDeletableEntity, IRemarkable, IExtendable
{
public string Remark { get; set; } = "";
public string Extend { get; set; } = "{}";
}
public abstract class HistoryEntity : Entity<Guid>, IHistoryEntry
{
public Guid? RelationId { get; set; }
public string EventType { get; set; } = "";
public string BeforeJson { get; set; } = "{}";
public string AfterJson { get; set; } = "{}";
public Guid? ContainerId { get; set; }
public string Operator { get; set; } = "";
public DateTimeOffset OperatedAt { get; set; }
public string Source { get; set; } = "Manual";
public string Reason { get; set; } = "";
public string Remark { get; set; } = "";
public string Extend { get; set; } = "{}";
}
@@ -0,0 +1,224 @@
using Microsoft.Extensions.Logging;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using MiGu.DB.Abstractions.Modules;
using MiGu.DB.Abstractions.Persistence;
using MiGu.DB.Abstractions.Providers;
using MiGu.DB.Abstractions.Runtime;
using MiGu.DB.Kernel.Context;
using MiGu.DB.Kernel.Conventions;
using MiGu.DB.Kernel.Providers;
using MiGu.DB.Kernel.Repositories;
using MiGu.DB.Domains.Migrators;
namespace MiGu.DB.Kernel.Hosting;
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddMiGuDb(
this IServiceCollection services,
IConfiguration configuration,
Action<MiGuDbOptions>? configure = null)
{
var options = new MiGuDbOptions
{
Provider = configuration["Database:Provider"] ?? "sqlite",
ConnectionString = configuration.GetConnectionString("Platform")
?? configuration.GetConnectionString(ConnectionKey(configuration["Database:Provider"] ?? "sqlite"))
?? "",
SchemaMode = ParseSchemaMode(configuration["Database:SchemaMode"]),
ApplyDataMigratorsOnStartup = configuration.GetValue("Database:ApplyDataMigratorsOnStartup", true)
};
configure?.Invoke(options);
services.AddSingleton(options);
services.TryAddSingleton<IActorContextAccessor, ActorContextAccessor>();
services.TryAddScoped<IActorContext>(sp => sp.GetRequiredService<IActorContextAccessor>().Current);
services.AddSingleton<AuditSaveChangesInterceptor>();
services.TryAddEnumerable(ServiceDescriptor.Singleton<IDbProviderSetup, SqliteProviderSetup>());
services.TryAddEnumerable(ServiceDescriptor.Singleton<IDbProviderSetup, MySqlProviderSetup>());
services.TryAddEnumerable(ServiceDescriptor.Singleton<IDbProviderSetup, NpgsqlProviderSetup>());
services.TryAddEnumerable(ServiceDescriptor.Singleton<IDbProviderSetup, SqlServerProviderSetup>());
services.AddDbContext<MiGuDbContext>((sp, builder) =>
{
var opt = sp.GetRequiredService<MiGuDbOptions>();
if (string.IsNullOrWhiteSpace(opt.ContentRootPath))
{
var env = sp.GetService<IHostEnvironment>();
opt.ContentRootPath = env?.ContentRootPath ?? AppContext.BaseDirectory;
}
var providerName = NormalizeProviderName(opt.Provider);
var setup = sp.GetServices<IDbProviderSetup>()
.FirstOrDefault(p => string.Equals(p.Name, providerName, StringComparison.OrdinalIgnoreCase))
?? throw new InvalidOperationException($"未知数据库 Provider: {opt.Provider}");
setup.Configure(builder, ResolveConnectionString(opt, providerName));
builder.AddInterceptors(sp.GetRequiredService<AuditSaveChangesInterceptor>());
});
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddScoped(typeof(IRepository<,>), typeof(Repository<,>));
services.AddScoped(typeof(IEditableRepository<>), typeof(EditableRepository<>));
services.AddScoped(typeof(IHistoryRepository<>), typeof(HistoryRepository<>));
services.AddMiGuDataMigrators();
return services;
}
public static IServiceCollection AddMiGuEntityModule<TModule>(this IServiceCollection services)
where TModule : class, IEntityModule, new()
{
services.TryAddEnumerable(ServiceDescriptor.Singleton<IEntityModule, TModule>());
new TModule().RegisterServices(services);
return services;
}
private static string NormalizeProviderName(string provider) => provider.Trim().ToLowerInvariant() switch
{
"postgres" or "postgresql" => "npgsql",
"mssql" => "sqlserver",
var x => x
};
private static MiGuSchemaMode ParseSchemaMode(string? value)
{
if (string.IsNullOrWhiteSpace(value)) return MiGuSchemaMode.Migrate;
if (Enum.TryParse<MiGuSchemaMode>(value.Trim(), ignoreCase: true, out var mode))
return mode;
// 兼容简写
return value.Trim().ToLowerInvariant() switch
{
"ensure" or "created" or "ensure-created" => MiGuSchemaMode.EnsureCreated,
"migrations" or "ef" => MiGuSchemaMode.Migrate,
_ => throw new InvalidOperationException(
$"未知 Database:SchemaMode '{value}',允许值:Migrate、EnsureCreated")
};
}
private static string ConnectionKey(string provider) => NormalizeProviderName(provider) switch
{
"npgsql" => "PostgreSQL",
"sqlserver" => "SqlServer",
"mysql" => "MySql",
_ => "Sqlite"
};
private static string ResolveConnectionString(MiGuDbOptions options, string providerName)
{
if (!string.IsNullOrWhiteSpace(options.ConnectionString))
{
return providerName == "sqlite"
? NormalizeSqliteConnection(options.ConnectionString, options.ContentRootPath)
: options.ConnectionString;
}
var dataDir = Path.Combine(options.ContentRootPath, "data");
Directory.CreateDirectory(dataDir);
return $"Data Source={Path.Combine(dataDir, "platform.db")}";
}
private static string NormalizeSqliteConnection(string connection, string contentRoot)
{
var builder = new SqliteConnectionStringBuilder(connection);
if (string.IsNullOrWhiteSpace(builder.DataSource) || builder.DataSource is ":memory:")
return connection;
if (!Path.IsPathRooted(builder.DataSource))
builder.DataSource = Path.Combine(contentRoot, builder.DataSource);
var dir = Path.GetDirectoryName(builder.DataSource);
if (!string.IsNullOrWhiteSpace(dir)) Directory.CreateDirectory(dir);
return builder.ToString();
}
}
public static class DatabaseInitializer
{
/// <summary>
/// 启动期数据库初始化:按 SchemaMode 建库/迁移,再可选执行 DataMigrator。
/// </summary>
public static async Task MigrateMiGuDbAsync(this IServiceProvider services, CancellationToken ct = default)
{
using var scope = services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<MiGuDbContext>();
var options = scope.ServiceProvider.GetRequiredService<MiGuDbOptions>();
var logger = scope.ServiceProvider.GetService<ILoggerFactory>()?.CreateLogger("MiGu.DB.DatabaseInitializer");
if (options.SchemaMode == MiGuSchemaMode.EnsureCreated)
{
logger?.LogWarning(
"Database:SchemaMode=EnsureCreated:仅按当前模型建库,不应用 Migrations。" +
"改实体后若结构未更新,请删除平台库文件后重启。发版请改用 Migrate。");
await db.Database.EnsureCreatedAsync(ct);
}
else
{
var applied = (await db.Database.GetAppliedMigrationsAsync(ct)).ToList();
var pending = (await db.Database.GetPendingMigrationsAsync(ct)).ToList();
if (applied.Count == 0 && pending.Count == 0)
{
logger?.LogWarning("程序集内无 Migration,回退 EnsureCreated。");
await db.Database.EnsureCreatedAsync(ct);
}
else
{
// 旧库(EnsureCreated)无历史表行时写入基线,再 Migrate
await BaselineExistingDatabaseAsync(db, logger, ct);
await db.Database.MigrateAsync(ct);
}
}
if (!options.ApplyDataMigratorsOnStartup) return;
foreach (var migrator in scope.ServiceProvider.GetServices<IDataMigrator>().OrderBy(m => m.Order))
await migrator.MigrateAsync(db, ct);
}
/// <summary>
/// 已有表结构但无 __EFMigrationsHistory 时:将<strong>全部</strong> pending Migration 记为已应用。
/// 前提:库由 EnsureCreated 按「当前模型 tip」建成,与最新 Snapshot 一致;否则应删库后走 Migrate,或手工对齐。
/// </summary>
private static async Task BaselineExistingDatabaseAsync(
MiGuDbContext db, ILogger? logger, CancellationToken ct)
{
var applied = await db.Database.GetAppliedMigrationsAsync(ct);
if (applied.Any()) return;
var pending = (await db.Database.GetPendingMigrationsAsync(ct)).ToList();
if (pending.Count == 0) return;
var creator = db.GetService<IRelationalDatabaseCreator>();
if (!await creator.ExistsAsync(ct) || !await creator.HasTablesAsync(ct))
return;
var history = db.GetService<IHistoryRepository>();
var productVersion = ProductInfo.GetEFCoreVersion();
logger?.LogWarning(
"检测到已有表且无迁移历史,将 {Count} 个 pending Migration 全部写入基线(假定库结构已对齐模型 tip):{Ids}",
pending.Count, string.Join(", ", pending));
foreach (var migrationId in pending)
{
var sql = history.GetInsertScript(new HistoryRow(migrationId, productVersion));
await db.Database.ExecuteSqlRawAsync(sql, ct);
}
}
}
internal static class ProductInfo
{
public static string GetEFCoreVersion()
{
var asm = typeof(DbContext).Assembly.GetName().Version;
return asm?.ToString(3) ?? "8.0.10";
}
}
@@ -0,0 +1,47 @@
using Microsoft.EntityFrameworkCore;
using MiGu.DB.Abstractions.Providers;
using MiGu.DB.Kernel.Context;
namespace MiGu.DB.Kernel.Providers;
public sealed class SqliteProviderSetup : IDbProviderSetup
{
public string Name => "sqlite";
public string MigrationsAssemblyName => typeof(MiGuDbContext).Assembly.GetName().Name!;
public string MigrationsNamespace => "MiGu.DB.Migrations.Sqlite";
public void Configure(DbContextOptionsBuilder builder, string connectionString)
=> builder.UseSqlite(connectionString, o => o.MigrationsAssembly(MigrationsAssemblyName)
.MigrationsHistoryTable("__EFMigrationsHistory"));
}
public sealed class MySqlProviderSetup : IDbProviderSetup
{
public string Name => "mysql";
public string MigrationsAssemblyName => typeof(MiGuDbContext).Assembly.GetName().Name!;
public string MigrationsNamespace => "MiGu.DB.Migrations.MySql";
public void Configure(DbContextOptionsBuilder builder, string connectionString)
=> builder.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString),
o => o.MigrationsAssembly(MigrationsAssemblyName));
}
public sealed class NpgsqlProviderSetup : IDbProviderSetup
{
public string Name => "npgsql";
public string MigrationsAssemblyName => typeof(MiGuDbContext).Assembly.GetName().Name!;
public string MigrationsNamespace => "MiGu.DB.Migrations.Npgsql";
public void Configure(DbContextOptionsBuilder builder, string connectionString)
=> builder.UseNpgsql(connectionString, o => o.MigrationsAssembly(MigrationsAssemblyName));
}
public sealed class SqlServerProviderSetup : IDbProviderSetup
{
public string Name => "sqlserver";
public string MigrationsAssemblyName => typeof(MiGuDbContext).Assembly.GetName().Name!;
public string MigrationsNamespace => "MiGu.DB.Migrations.SqlServer";
public void Configure(DbContextOptionsBuilder builder, string connectionString)
=> builder.UseSqlServer(connectionString, o => o.MigrationsAssembly(MigrationsAssemblyName));
}
+116
View File
@@ -0,0 +1,116 @@
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using MiGu.DB.Abstractions.Entities;
using MiGu.DB.Abstractions.Exceptions;
using MiGu.DB.Abstractions.Persistence;
using MiGu.DB.Abstractions.Runtime;
using MiGu.DB.Kernel.Context;
namespace MiGu.DB.Kernel.Repositories;
public class Repository<TEntity, TKey> : IRepository<TEntity, TKey>
where TEntity : class, IEntity<TKey>
{
protected readonly MiGuDbContext Db;
protected DbSet<TEntity> Set => Db.Set<TEntity>();
public Repository(MiGuDbContext db) => Db = db;
public virtual IQueryable<TEntity> Query(bool asNoTracking = true)
=> asNoTracking ? Set.AsNoTracking() : Set.AsQueryable();
public virtual Task<TEntity?> FindAsync(TKey id, CancellationToken ct = default)
=> Set.FindAsync([id], ct).AsTask();
public virtual Task AddAsync(TEntity entity, CancellationToken ct = default)
=> Set.AddAsync(entity, ct).AsTask();
public virtual void Update(TEntity entity) => Set.Update(entity);
}
public sealed class EditableRepository<TEntity> : Repository<TEntity, Guid>, IEditableRepository<TEntity>
where TEntity : class, IEntity<Guid>, ISoftDeletable, IVersioned, ILockable
{
private readonly IActorContextAccessor _actors;
public EditableRepository(MiGuDbContext db, IActorContextAccessor actors) : base(db)
=> _actors = actors;
public async Task<TEntity> GetEditableAsync(Guid id, long? expectedVersion, CancellationToken ct = default)
{
var entity = await Set.FirstOrDefaultAsync(x => x.Id.Equals(id), ct)
?? throw new EntityNotFoundException(typeof(TEntity).Name, id);
if (entity.IsLock)
throw new EntityLockedException(typeof(TEntity).Name, id);
if (expectedVersion.HasValue && entity.Version != expectedVersion.Value)
throw new ConcurrencyConflictException(typeof(TEntity).Name, id, expectedVersion);
return entity;
}
public async Task SoftDeleteAsync(Guid id, long? expectedVersion, CancellationToken ct = default)
{
var entity = await GetEditableAsync(id, expectedVersion, ct);
entity.IsDeleted = true;
entity.DeletedAt = DateTimeOffset.UtcNow;
entity.DeletedBy = _actors.Current.Name;
if (entity is IAuditable auditable)
auditable.UpdatedBy = _actors.Current.Name;
}
public async Task EnsureUniqueAsync(Expression<Func<TEntity, bool>> predicate, string errorMessage, CancellationToken ct = default)
{
if (await Set.AnyAsync(predicate, ct))
throw new InvalidOperationException(errorMessage);
}
}
public sealed class HistoryRepository<TEntity> : Repository<TEntity, Guid>, IHistoryRepository<TEntity>
where TEntity : class, IEntity<Guid>, IHistoryEntry
{
public HistoryRepository(MiGuDbContext db) : base(db) { }
public Task AppendAsync(TEntity entry, CancellationToken ct = default)
=> AddAsync(entry, ct);
}
public sealed class UnitOfWork : IUnitOfWork
{
private readonly MiGuDbContext _db;
public UnitOfWork(MiGuDbContext db) => _db = db;
public async Task<int> SaveChangesAsync(CancellationToken ct = default)
{
try
{
return await _db.SaveChangesAsync(ct);
}
catch (DbUpdateConcurrencyException ex)
{
var entry = ex.Entries.FirstOrDefault();
throw new ConcurrencyConflictException(
entry?.Entity.GetType().Name ?? "Unknown",
entry?.Property("Id")?.CurrentValue);
}
}
public Task ExecuteInTransactionAsync(Func<CancellationToken, Task> action, CancellationToken ct = default)
{
var strategy = _db.Database.CreateExecutionStrategy();
return strategy.ExecuteAsync(async () =>
{
await using var tx = await _db.Database.BeginTransactionAsync(ct);
try
{
await action(ct);
await _db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
}
catch
{
await tx.RollbackAsync(ct);
throw;
}
});
}
}