12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- using DataTransmission.Enum;
- 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;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- namespace SnapshotWinFormsApp.Application.Interfaces;
- public class ImportApplicationBase<TSource, TEntity, TKey> : IImportApplication
- where TSource : OldBaseEntity<TKey>, new()
- where TEntity : Entity, new()
- {
- private readonly IRepository<TSource, TKey> _sourceRepo;
- private readonly IBaseRepository<TEntity> _targetRepo;
- private readonly IBaseRepository<OldDataId> _oldDataIdRepo;
- private readonly SqlSugarClient _sugarClient;
- private readonly CreateInstanceInDto _instance;
- public ImportApplicationBase(CreateInstanceInDto inDto)
- {
- _instance = inDto;
- _sourceRepo = new Repository<TSource, TKey>(inDto);
- _targetRepo = new BaseRepository<TEntity>(inDto);
- _oldDataIdRepo = new BaseRepository<OldDataId>(inDto);
- }
- public async Task ImportAsync(Action<string> log, CancellationToken token)
- {
- log($"正在查询旧数据...");
- var items = await GetSourceList(_instance).ToListAsync(token);
- log($"共查询到{items.Count}条数据");
- var tableName = typeof(TSource).GetCustomAttribute<SugarTable>()?.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 = HasOldData(tableName, item);
- if (has) continue;
- var target = item.Adapt<TEntity>();
- await _targetRepo.db.Ado.BeginTranAsync();
- target.Id = _targetRepo.InsertBulk(target, i + 1 == items.Count);
- await _oldDataIdRepo.InsertAsync(new OldDataId { OldId = item.Id.ToString(), TableName = tableName, NewId = target.Id }, token);
- await _targetRepo.db.Ado.CommitTranAsync();
- log($"{i}/{items.Count} 插入数据: {item.Id} {target.Id}");
- }
- }
- public virtual ISugarQueryable<TSource> GetSourceList(CreateInstanceInDto inDto)
- {
- return _sourceRepo.Queryable();
- }
- public virtual bool HasOldData(string tableName, TSource item)
- {
- return _oldDataIdRepo.Queryable().Any(m => m.TableName == tableName && item.Id.ToString() == m.OldId);
- }
- }
|