1
0

SyncData.cs 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. using System;
  2. using System.Linq;
  3. using System.Threading.Tasks;
  4. using System.IO;
  5. using Newtonsoft.Json;
  6. using FreeSql;
  7. using FreeSql.DataAnnotations;
  8. using ZhonTai.Common.Helpers;
  9. using ZhonTai.Admin.Core.Configs;
  10. namespace ZhonTai.Admin.Core.Db;
  11. public abstract class SyncData
  12. {
  13. /// <summary>
  14. /// 检查实体属性是否为自增长
  15. /// </summary>
  16. /// <typeparam name="T"></typeparam>
  17. /// <returns></returns>
  18. private bool CheckIdentity<T>() where T : class
  19. {
  20. var isIdentity = false;
  21. var properties = typeof(T).GetProperties();
  22. foreach (var property in properties)
  23. {
  24. if (property.GetCustomAttributes(typeof(ColumnAttribute), false).FirstOrDefault() is ColumnAttribute columnAttribute && columnAttribute.IsIdentity)
  25. {
  26. isIdentity = true;
  27. break;
  28. }
  29. }
  30. return isIdentity;
  31. }
  32. /// <summary>
  33. /// 初始化数据表数据
  34. /// </summary>
  35. /// <typeparam name="T"></typeparam>
  36. /// <param name="db"></param>
  37. /// <param name="unitOfWork"></param>
  38. /// <param name="tran"></param>
  39. /// <param name="data"></param>
  40. /// <param name="dbConfig"></param>
  41. /// <returns></returns>
  42. protected virtual async Task InitDataAsync<T>(
  43. IFreeSql db,
  44. IUnitOfWork unitOfWork,
  45. System.Data.Common.DbTransaction tran,
  46. T[] data,
  47. DbConfig dbConfig = null
  48. ) where T : class, new()
  49. {
  50. var table = typeof(T).GetCustomAttributes(typeof(TableAttribute), false).FirstOrDefault() as TableAttribute;
  51. var tableName = table.Name;
  52. try
  53. {
  54. if (await db.Queryable<T>().AnyAsync())
  55. {
  56. Console.WriteLine($" table: {tableName} record already exists");
  57. return;
  58. }
  59. if (!(data?.Length > 0))
  60. {
  61. Console.WriteLine($" table: {tableName} import data []");
  62. return;
  63. }
  64. var repo = db.GetRepository<T>();
  65. var insert = db.Insert<T>();
  66. if (unitOfWork != null)
  67. {
  68. repo.UnitOfWork = unitOfWork;
  69. insert = insert.WithTransaction(tran);
  70. }
  71. var isIdentity = CheckIdentity<T>();
  72. if (isIdentity)
  73. {
  74. if (dbConfig.Type == DataType.SqlServer)
  75. {
  76. var insrtSql = insert.AppendData(data).InsertIdentity().ToSql();
  77. await repo.Orm.Ado.ExecuteNonQueryAsync($"SET IDENTITY_INSERT {tableName} ON\n {insrtSql} \nSET IDENTITY_INSERT {tableName} OFF");
  78. }
  79. else
  80. {
  81. await insert.AppendData(data).InsertIdentity().ExecuteAffrowsAsync();
  82. }
  83. }
  84. else
  85. {
  86. repo.DbContextOptions.EnableCascadeSave = true;
  87. await repo.InsertAsync(data);
  88. }
  89. Console.WriteLine($" table: {tableName} sync data succeed");
  90. }
  91. catch (Exception ex)
  92. {
  93. Console.WriteLine($" table: {tableName} sync data failed.\n{ex.Message}");
  94. throw;
  95. }
  96. }
  97. protected virtual T[] GetData<T>(bool isTenant = false, string path = "InitData/Admin")
  98. {
  99. var table = typeof(T).GetCustomAttributes(typeof(TableAttribute), false).FirstOrDefault() as TableAttribute;
  100. var fileName = $"{table.Name}{(isTenant ? ".tenant" : "")}.json";
  101. var filePath = Path.Combine(AppContext.BaseDirectory, $"{path}/{fileName}").ToPath();
  102. if (!File.Exists(filePath))
  103. {
  104. var msg = $"文件{filePath}不存在";
  105. Console.WriteLine(msg);
  106. throw new Exception(msg);
  107. }
  108. var jsonData = FileHelper.ReadFile(filePath);
  109. var data = JsonConvert.DeserializeObject<T[]>(jsonData);
  110. return data;
  111. }
  112. }