当前位置:Gxlcms > 数据库问题 > EFCore CodeFirst模型迁移生成数据库备注(mysql)

EFCore CodeFirst模型迁移生成数据库备注(mysql)

时间:2021-07-01 10:21:17 帮助过:99人阅读

重写Mysql下sql脚本生成器

  1. <code>using Framework.NetCore.Extensions;
  2. using Framework.NetCore.Models;
  3. using Microsoft.EntityFrameworkCore.Metadata;
  4. using Microsoft.EntityFrameworkCore.Migrations;
  5. using Microsoft.EntityFrameworkCore.Migrations.Operations;
  6. using Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Reflection;
  12. using System.Text;
  13. namespace Framework.NetCore.EfDbContext
  14. {
  15. public class MyMigrationsSqlGenerator : MySqlMigrationsSqlGenerator
  16. {
  17. public MyMigrationsSqlGenerator(
  18. MigrationsSqlGeneratorDependencies dependencies,
  19. IMigrationsAnnotationProvider migrationsAnnotations,
  20. IMySqlOptions mySqlOptions)
  21. : base(dependencies, migrationsAnnotations, mySqlOptions)
  22. {
  23. }
  24. protected override void Generate(MigrationOperation operation, IModel model, MigrationCommandListBuilder builder)
  25. {
  26. base.Generate(operation, model, builder);
  27. if (operation is CreateTableOperation || operation is AlterTableOperation)
  28. CreateTableComment(operation, model, builder);
  29. if (operation is AddColumnOperation || operation is AlterColumnOperation)
  30. CreateColumnComment(operation, model, builder);
  31. }
  32. /// <summary>
  33. /// Create table comment.
  34. /// </summary>
  35. /// <param name="operation"></param>
  36. /// <param name="builder"></param>
  37. private void CreateTableComment(MigrationOperation operation, IModel model, MigrationCommandListBuilder builder)
  38. {
  39. string tableName = string.Empty;
  40. string description = string.Empty;
  41. if (operation is AlterTableOperation)
  42. {
  43. var t = operation as AlterColumnOperation;
  44. tableName = (operation as AlterTableOperation).Name;
  45. }
  46. if (operation is CreateTableOperation)
  47. {
  48. var t = operation as CreateTableOperation;
  49. var addColumnsOperation = t.Columns;
  50. tableName = (operation as CreateTableOperation).Name;
  51. foreach (var item in addColumnsOperation)
  52. {
  53. CreateColumnComment(item, model, builder);
  54. }
  55. }
  56. description = DbDescriptionHelper.GetDescription(tableName);
  57. if (tableName.IsNullOrWhiteSpace())
  58. throw new Exception("Create table comment error.");
  59. var sqlHelper = Dependencies.SqlGenerationHelper;
  60. builder
  61. .Append("ALTER TABLE ")
  62. .Append(sqlHelper.DelimitIdentifier(tableName).ToLower())
  63. .Append(" COMMENT ")
  64. .Append("'")
  65. .Append(description)
  66. .Append("'")
  67. .AppendLine(sqlHelper.StatementTerminator)
  68. .EndCommand();
  69. }
  70. /// <summary>
  71. /// Create column comment.
  72. /// </summary>
  73. /// <param name="operation"></param>
  74. /// <param name="builder"></param>
  75. private void CreateColumnComment(MigrationOperation operation, IModel model, MigrationCommandListBuilder builder)
  76. {
  77. //alter table a1log modify column UUID VARCHAR(26) comment '修改后的字段注释';
  78. string tableName = string.Empty;
  79. string columnName = string.Empty;
  80. string columnType = string.Empty;
  81. string description = string.Empty;
  82. if (operation is AlterColumnOperation)
  83. {
  84. var t = (operation as AlterColumnOperation);
  85. tableName = t.Table;
  86. columnName = t.Name;
  87. columnType = GetColumnType(t.Schema, t.Table, t.Name, t.ClrType, t.IsUnicode, t.MaxLength, t.IsFixedLength, t.IsRowVersion, model);
  88. }
  89. if (operation is AddColumnOperation)
  90. {
  91. var t = (operation as AddColumnOperation);
  92. tableName = t.Table;
  93. columnName = t.Name;
  94. columnType = GetColumnType(t.Schema, t.Table, t.Name, t.ClrType, t.IsUnicode, t.MaxLength, t.IsFixedLength, t.IsRowVersion, model);
  95. description = DbDescriptionHelper.GetDescription(tableName, columnName);
  96. }
  97. if (columnName.IsNullOrWhiteSpace() || tableName.IsNullOrWhiteSpace() || columnType.IsNullOrWhiteSpace())
  98. throw new Exception("Create columnt comment error." + columnName + "/" + tableName + "/" + columnType);
  99. var sqlHelper = Dependencies.SqlGenerationHelper;
  100. builder
  101. .Append("ALTER TABLE ")
  102. .Append(sqlHelper.DelimitIdentifier(tableName).ToLower())
  103. .Append(" MODIFY COLUMN ")
  104. .Append(columnName)
  105. .Append(" ")
  106. .Append(columnType)
  107. .Append(" COMMENT ")
  108. .Append("'")
  109. .Append(description)
  110. .Append("'")
  111. .AppendLine(sqlHelper.StatementTerminator)
  112. .EndCommand();
  113. }
  114. }
  115. public class DbDescriptionHelper
  116. {
  117. public static string b { get; set; } = "Framework.Website.Models";
  118. public static string c { get; set; } = @"C:\Users\fxy75\Downloads\pos3.0\Framework.Website.Models";
  119. public static List<DbDescription> list { get; set; }
  120. public static string GetDescription(string table, string column = "")
  121. {
  122. if (list == null || list.Count() == 0)
  123. {
  124. list = GetDescription();
  125. }
  126. if (!string.IsNullOrWhiteSpace(table))
  127. {
  128. if (string.IsNullOrWhiteSpace(column))
  129. {
  130. var x = list.FirstOrDefault(p => p.Name == table);
  131. if (x != null)
  132. return x.Description;
  133. return string.Empty;
  134. }
  135. else
  136. {
  137. var x = list.FirstOrDefault(p => p.Name == table);
  138. if (x != null)
  139. {
  140. var y = x.Column;
  141. if (y.IsNotNull())
  142. {
  143. var z = y.FirstOrDefault(p => p.Name == column);
  144. if (z != null)
  145. return z.Description;
  146. }
  147. }
  148. return string.Empty;
  149. }
  150. }
  151. else
  152. return string.Empty;
  153. }
  154. public static List<DbDescription> GetDescription()
  155. {
  156. var d = new List<DbDescription>();
  157. var e = Assembly.Load(b);
  158. var f = e?.GetTypes();
  159. var g = f?
  160. .Where(t => t.IsClass
  161. && !t.IsGenericType
  162. && !t.IsAbstract
  163. && t.GetInterfaces().Any(m => m.GetGenericTypeDefinition() == typeof(IBaseModel<>))
  164. ).ToList();
  165. foreach (var h in g)
  166. {
  167. var i = new DbDescription();
  168. var j = c + "\\" + h.Name + ".cs";
  169. var k = File.ReadAllText(j);
  170. k = k.Substring(k.IndexOf("{") + 1, k.LastIndexOf("}") - k.IndexOf("{") - 1).Replace("\n", "");
  171. var l = k.Substring(k.IndexOf(" {") + 2, k.LastIndexOf(" }") - k.IndexOf(" {") - 1).Replace("\n", "");
  172. string[] slipt = { "}\r" };
  173. var m = l.Split(slipt, StringSplitOptions.None).ToList();
  174. var n = new List<DbDescription>();
  175. foreach (var o in m)
  176. {
  177. var p = o.Replace("///", "");
  178. var q = p.IndexOf("<summary>");
  179. var r = p.LastIndexOf("</summary>");
  180. var s = p.IndexOf("public");
  181. var t = p.IndexOf("{");
  182. var u = (q > 0 && r > 0) ? p.Substring(q + 9, r - q - 10).Replace("\r", "").Replace(" ", "") : "";
  183. var v = (s > 0 && t > 0) ? p.Substring(s, t - s).Split(' ')[2] : "";
  184. n.Add(new DbDescription()
  185. {
  186. Description = u,
  187. Name = v
  188. });
  189. }
  190. var w = k.Substring(0, k.IndexOf("{\r") - 1);
  191. w = w.Replace("///", "");
  192. var x = w.IndexOf("<summary>");
  193. var y = w.LastIndexOf("</summary>");
  194. var z = (x > 0 && y > 0) ? w.Substring(x + 9, y - x - 10).Replace("\r", "").Replace(" ", "") : "";
  195. d.Add(new DbDescription()
  196. {
  197. Name = h.Name,
  198. Description = z,
  199. Column = n
  200. });
  201. }
  202. return d;
  203. }
  204. }
  205. public class DbDescription
  206. {
  207. public string Name { get; set; }
  208. public string Description { get; set; }
  209. public List<DbDescription> Column { get; set; }
  210. }
  211. }</code>

EFCore DbContext中替换IMigrationsSqlGenerator

  1. <code>protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  2. {
  3. optionsBuilder
  4. .UseMySql(_option.ConnectionString)
  5. .ReplaceService<IMigrationsSqlGenerator, MyMigrationsSqlGenerator>();
  6. base.OnConfiguring(optionsBuilder);
  7. }</code>

EFCore CodeFirst模型迁移生成数据库备注(mysql)

标签:leo   char   netcore   hit   unicode   sum   ace   and   pomelo   

人气教程排行