using Mapster; using SnapshotWinFormsApp.Application.Dtos; using SnapshotWinFormsApp.Entities.NewHotline; using SnapshotWinFormsApp.Entities.OldHotline; using SnapshotWinFormsApp.Repository; using SnapshotWinFormsApp.Repository.Interfaces; using SqlSugar; using System.Reflection; namespace SnapshotWinFormsApp.Application.Interfaces; public class ImportApplicationBase : ImportApplicationBase where TSource : OldBaseEntity, new() where TEntity : Entity, new() { public ImportApplicationBase(CreateInstanceInDto inDto) : base(inDto) { } } public class ImportApplicationBase : IImportApplication where TSource : OldBaseEntity, new() where TEntity : Entity, new() where TMix : OldBaseEntity, new() { public readonly IRepository _sourceRepo; public readonly IBaseRepository _targetRepo; public readonly IBaseRepository _oldDataIdRepo; public readonly SqlSugarClient _sugarClient; public readonly CreateInstanceInDto _instance; public ImportApplicationBase(CreateInstanceInDto inDto) { _instance = inDto; _sourceRepo = new Repository(inDto); _targetRepo = new BaseRepository(inDto); _oldDataIdRepo = new BaseRepository(inDto); } public async Task ImportAsync(Action log, CancellationToken token) { log($"正在查询旧数据..."); var items = await GetSourceList(_instance).ToListAsync(token); log($"共查询到{items.Count}条数据"); var tableName = typeof(TSource).GetCustomAttribute()?.TableName ?? throw new ArgumentNullException("老数据表名不能为空, 设置[SugarTable()]"); for (int i = 0;i < items.Count;i++) { await Task.Run(() => MainForm._pauseEvent.WaitHandle.WaitOne(), token); var item = items[i]; var has = await HasOldDataAsync(tableName, item, token); if (has) continue; var target = await GetTargetAsync(item, token); await _targetRepo.db.Ado.BeginTranAsync(); target.Id = _targetRepo.InsertBulk(target, i + 1 == items.Count); _oldDataIdRepo.InsertBulk(new OldDataId { OldId = item.Id.ToString(), TableName = tableName, NewId = target.Id }, i + 1 == items.Count); await _targetRepo.db.Ado.CommitTranAsync(); log($"{i}/{items.Count} 插入数据: {item.Id} {target.Id}"); await InsertAfterAsync(log, item, target, token); } } /// /// 插入数据以后执行的动作 /// /// /// /// /// /// public virtual async Task InsertAfterAsync(Action log, TMix item, TEntity target, CancellationToken token) { await Task.FromResult(0); } /// /// 获取原始数据集合 /// /// /// public virtual ISugarQueryable GetSourceList(CreateInstanceInDto inDto) { return _sourceRepo.Queryable(); } /// /// 获取原始数据集合 /// /// /// public virtual ISugarQueryable GetSourceList() { throw new NotImplementedException(); } /// /// 根据原始数据获取目标数据 /// /// /// public virtual async Task GetTargetAsync(TMix source, CancellationToken token) { return await Task.FromResult(source.Adapt()); } /// /// 验证是否已存在 /// /// /// /// public virtual async Task HasOldDataAsync(string tableName, TMix item, CancellationToken token) { return await _oldDataIdRepo.Queryable().AnyAsync(m => m.TableName == tableName && item.Id.ToString() == m.OldId, token); } }