Files
Migu2.0/MiGu.DB/Kernel/Repositories/Repositories.cs
T
wei.wu 51c3fc1994 持久层重构为独立 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 追踪数据库结构
- 优化代码结构,解耦领域与持久层,提升扩展性与安全性
2026-07-27 14:26:04 +08:00

117 lines
4.1 KiB
C#

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;
}
});
}
}