SqlSugarStartupExtensions.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. using System.ComponentModel;
  2. using System.ComponentModel.DataAnnotations;
  3. using System.Reflection;
  4. using Microsoft.Extensions.Configuration;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using Microsoft.Extensions.Logging;
  7. using Serilog;
  8. using SqlSugar;
  9. using XF.Domain;
  10. using XF.Domain.Entities;
  11. using XF.Domain.Extensions;
  12. namespace CallCenter.Repository.SqlSugar
  13. {
  14. public static class SqlSugarStartupExtensions
  15. {
  16. public static void AddSqlSugar(this IServiceCollection services, IConfiguration configuration, string dbName = "CallCenter")
  17. {
  18. //多租户 new SqlSugarScope(List<ConnectionConfig>,db=>{});
  19. SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
  20. {
  21. DbType = DbType.MySql,
  22. ConnectionString = configuration.GetConnectionString(dbName),
  23. IsAutoCloseConnection = true,
  24. ConfigureExternalServices = new ConfigureExternalServices
  25. {
  26. EntityService = (property, column) =>
  27. {
  28. var attributes = property.GetCustomAttributes(true);//get all attributes
  29. //if (attributes.Any(it => it is KeyAttribute))// by attribute set primarykey
  30. //{
  31. // column.IsPrimarykey = true; //有哪些特性可以看 1.2 特性明细
  32. //}
  33. ////可以写多个,这边可以断点调试
  34. //// if (attributes.Any(it => it is NotMappedAttribute))
  35. ////{
  36. //// column.IsIgnore= true;
  37. ////}
  38. //if (attributes.Any(it => it is DbNullableAttribute))
  39. //{
  40. // column.IsNullable = true;
  41. //}
  42. //if (attributes.Any(it => it is DbJsonAttribute))
  43. //{
  44. // column.DataType = "varchar(3000)";
  45. // column.IsJson = true;
  46. //}
  47. //if (attributes.Any(it => it is DbLengthAttribute))
  48. //{
  49. // column.Length = (attributes.First(d => d is DbLengthAttribute) as DbLengthAttribute)?.MaxLength ?? 255;
  50. //}
  51. //if (attributes.Any(it => it is DbIgnoreAttribute))
  52. //{
  53. // column.IsIgnore = true;
  54. //}
  55. if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
  56. {
  57. column.IsNullable = true;
  58. }
  59. if (column.PropertyName.ToLower() == "id" || attributes.Any(it => it is KeyAttribute)) //是id的设为主键
  60. {
  61. column.IsPrimarykey = true;
  62. column.Length = 36;
  63. }
  64. //column.ColumnDescription = (attributes.FirstOrDefault(d => d is DescriptionAttribute) as DescriptionAttribute)?.Description ?? string.Empty;
  65. },
  66. EntityNameService = (type, entity) =>
  67. {
  68. var attributes = type.GetCustomAttributes(true);
  69. //if (attributes.Any(it => it is TableAttribute))
  70. //{
  71. // entity.DbTableName = (attributes.First(it => it is TableAttribute) as TableAttribute).Name;
  72. //}
  73. entity.DbTableName = entity.DbTableName.ToSnakeCase();
  74. if (attributes.Any(d => d is DescriptionAttribute))
  75. {
  76. entity.TableDescription =
  77. (attributes.First(d => d is DescriptionAttribute) as DescriptionAttribute).Description;
  78. }
  79. }
  80. }
  81. },
  82. db =>
  83. {
  84. /***写AOP等方法***/
  85. db.Aop.OnLogExecuting = (sql, pars) =>
  86. {
  87. //Log.Information(sql);
  88. };
  89. db.Aop.OnError = (exp) =>//SQL报错
  90. {
  91. //exp.sql 这样可以拿到错误SQL,性能无影响拿到ORM带参数使用的SQL
  92. Log.Error("SqlError: {0}", exp.Sql);
  93. //5.0.8.2 获取无参数化 SQL 对性能有影响,特别大的SQL参数多的,调试使用
  94. //UtilMethods.GetSqlString(DbType.SqlServer,exp.sql,exp.parameters)
  95. };
  96. db.Aop.OnExecutingChangeSql = (sql, pars) => //可以修改SQL和参数的值
  97. {
  98. //sql=newsql
  99. //foreach(var p in pars) //修改
  100. return new KeyValuePair<string, SugarParameter[]>(sql, pars);
  101. };
  102. db.Aop.OnLogExecuted = (sql, p) =>
  103. {
  104. //执行时间超过1秒
  105. if (db.Ado.SqlExecutionTime.TotalSeconds > 1)
  106. {
  107. //代码CS文件名
  108. var fileName = db.Ado.SqlStackTrace.FirstFileName;
  109. //代码行数
  110. var fileLine = db.Ado.SqlStackTrace.FirstLine;
  111. //方法名
  112. var FirstMethodName = db.Ado.SqlStackTrace.FirstMethodName;
  113. //db.Ado.SqlStackTrace.MyStackTraceList[1].xxx 获取上层方法的信息
  114. Log.Warning("slow query ==> fileName: {fileName}, fileLine: {fileLine}, FirstMethodName: {FirstMethodName}",
  115. fileName, fileLine, FirstMethodName);
  116. }
  117. //相当于EF的 PrintToMiniProfiler
  118. };
  119. db.Aop.DataExecuting = (oldValue, entityInfo) =>
  120. {
  121. //inset生效
  122. if (entityInfo.PropertyName == "CreationTime" && entityInfo.OperationType == DataFilterType.InsertByObject)
  123. {
  124. entityInfo.SetValue(DateTime.Now);//修改CreateTime字段
  125. //entityInfo有字段所有参数
  126. }
  127. //update生效
  128. else if (entityInfo.PropertyName == "LastModificationTime" && entityInfo.OperationType == DataFilterType.UpdateByObject)
  129. {
  130. entityInfo.SetValue(DateTime.Now);//修改UpdateTime字段
  131. }
  132. //根据当前列修改另一列 可以么写
  133. //if(当前列逻辑==XXX)
  134. //var properyDate = entityInfo.EntityValue.GetType().GetProperty("Date");
  135. //if(properyDate!=null)
  136. //properyDate.SetValue(entityInfo.EntityValue,1);
  137. else if (entityInfo.EntityColumnInfo.IsPrimarykey
  138. && entityInfo.EntityColumnInfo.PropertyName.ToLower() == "id"
  139. && entityInfo.OperationType == DataFilterType.InsertByObject) //通过主键保证只进一次事件
  140. {
  141. //这样每条记录就只执行一次
  142. entityInfo.SetValue(SequentialStringGenerator.Create());
  143. }
  144. };
  145. });
  146. ISugarUnitOfWork<CallCenterDbContext> context = new SugarUnitOfWork<CallCenterDbContext>(sqlSugar);
  147. ////全局过滤
  148. //var deletionTypes = AppDomain.CurrentDomain.GetAssemblies().ToList()
  149. // .SelectMany(d=>d.GetTypes()).Where(d=>d.GetInterfaces()/*.Any(x=>x == typeof(ISoftDelete))*/);//todo 找出即实现ISoftDelete 又实现IEntity
  150. //foreach (var deletionType in deletionTypes)
  151. //{
  152. //}
  153. services.AddSingleton<ISugarUnitOfWork<CallCenterDbContext>>(context);
  154. }
  155. }
  156. }