SyncData.cs 4.3 KB

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