ImportApplicationBase.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using DataTransmission.Enum;
  2. using Mapster;
  3. using SnapshotWinFormsApp.Application.Dtos;
  4. using SnapshotWinFormsApp.Entities.NewHotline;
  5. using SnapshotWinFormsApp.Entities.OldHotline;
  6. using SnapshotWinFormsApp.Repository;
  7. using SnapshotWinFormsApp.Repository.Interfaces;
  8. using SqlSugar;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Reflection;
  13. using System.Text;
  14. using System.Threading.Tasks;
  15. namespace SnapshotWinFormsApp.Application.Interfaces;
  16. public class ImportApplicationBase<TSource, TEntity, TKey> : IImportApplication
  17. where TSource : OldBaseEntity<TKey>, new()
  18. where TEntity : Entity, new()
  19. {
  20. private readonly IRepository<TSource, TKey> _sourceRepo;
  21. private readonly IBaseRepository<TEntity> _targetRepo;
  22. private readonly IBaseRepository<OldDataId> _oldDataIdRepo;
  23. private readonly SqlSugarClient _sugarClient;
  24. private readonly CreateInstanceInDto _instance;
  25. public ImportApplicationBase(CreateInstanceInDto inDto)
  26. {
  27. _instance = inDto;
  28. _sourceRepo = new Repository<TSource, TKey>(inDto);
  29. _targetRepo = new BaseRepository<TEntity>(inDto);
  30. _oldDataIdRepo = new BaseRepository<OldDataId>(inDto);
  31. }
  32. public async Task ImportAsync(Action<string> log, CancellationToken token)
  33. {
  34. log($"正在查询旧数据...");
  35. var items = await GetSourceList(_instance).ToListAsync(token);
  36. log($"共查询到{items.Count}条数据");
  37. var tableName = typeof(TSource).GetCustomAttribute<SugarTable>()?.TableName ?? throw new ArgumentNullException("老数据表名不能为空, 设置[SugarTable()]");
  38. for (int i = 0;i < items.Count;i++)
  39. {
  40. await Task.Run(() => MainForm._pauseEvent.WaitHandle.WaitOne(), token);
  41. var item = items[i];
  42. var has = HasOldData(tableName, item);
  43. if (has) continue;
  44. var target = item.Adapt<TEntity>();
  45. await _targetRepo.db.Ado.BeginTranAsync();
  46. target.Id = _targetRepo.InsertBulk(target, i + 1 == items.Count);
  47. await _oldDataIdRepo.InsertAsync(new OldDataId { OldId = item.Id.ToString(), TableName = tableName, NewId = target.Id }, token);
  48. await _targetRepo.db.Ado.CommitTranAsync();
  49. log($"{i}/{items.Count} 插入数据: {item.Id} {target.Id}");
  50. }
  51. }
  52. public virtual ISugarQueryable<TSource> GetSourceList(CreateInstanceInDto inDto)
  53. {
  54. return _sourceRepo.Queryable();
  55. }
  56. public virtual bool HasOldData(string tableName, TSource item)
  57. {
  58. return _oldDataIdRepo.Queryable().Any(m => m.TableName == tableName && item.Id.ToString() == m.OldId);
  59. }
  60. }