基础服务api
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

80 lines
3.3 KiB

  1. using BPA.SAAS.Manage.Comm.Const;
  2. using BPA.SAAS.Manage.Core.Base;
  3. using Furion;
  4. using Microsoft.Extensions.Configuration;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using SqlSugar;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Text.RegularExpressions;
  11. namespace BPA.SAAS.Manage.Core
  12. {
  13. /// <summary>
  14. /// 数据库上下文对象
  15. /// </summary>
  16. public static class DbContext
  17. {
  18. /// <summary>
  19. /// SqlSugar 数据库实例
  20. /// </summary>
  21. public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration)
  22. {
  23. var connectionConfigs = App.GetConfig<List<ConnectionConfig>>("ConnectionConfigs");
  24. //如果多个数数据库传 List<ConnectionConfig>
  25. var configConnection = new ConnectionConfig()
  26. {
  27. ConnectionString = connectionConfigs[0].ConnectionString,
  28. DbType = DbType.MySql,//设置数据库类型
  29. IsAutoCloseConnection = true,//自动释放数据务,如果存在事务,在事务结束后释放
  30. InitKeyType = InitKeyType.Attribute, //从实体特性中读取主键自增列信息
  31. ConfigId = "default",
  32. };
  33. SqlSugarScope sqlSugar = new SqlSugarScope(configConnection,
  34. db =>
  35. {
  36. db.Aop.DataExecuting = (oldValue, entityInfo) =>
  37. {
  38. //新增添加加盟商id赋值
  39. var groupId = App.User?.FindFirst(ClaimConst.GroupId)?.Value;
  40. if (entityInfo.PropertyName == "GroupId" && entityInfo.OperationType == DataFilterType.InsertByObject)
  41. {
  42. if (oldValue == null || oldValue == Convert.DBNull)
  43. {
  44. entityInfo.SetValue(groupId);
  45. }
  46. }
  47. };
  48. //单例参数配置,所有上下文生效
  49. db.Aop.OnLogExecuting = (sql, pars) =>
  50. {
  51. //过滤已删除数据
  52. db.QueryFilter.AddTableFilter<IDeleted>(it => it.IsDeleted == 0);
  53. if (!IsSuperAdmin())
  54. {
  55. //非管理员账户过滤加盟商数据
  56. var groupId = App.User?.FindFirst(ClaimConst.GroupId)?.Value;
  57. db.QueryFilter.AddTableFilter<IGroupId>(it => it.GroupId == groupId);
  58. }
  59. //Console.WriteLine(sql);//输出sql
  60. Console.WriteLine($"当前SQL语句:【{sql}】,参数:【{string.Join(",", pars.Select(t => t.Value))}】");
  61. };
  62. });
  63. services.AddSingleton<ISqlSugarClient>(sqlSugar);//这边是SqlSugarScope用AddSingleton
  64. }
  65. // <summary>
  66. /// 判断是不是超级管理员
  67. /// </summary>
  68. /// <returns></returns>
  69. private static bool IsSuperAdmin()
  70. {
  71. if (App.User == null) return false;
  72. return App.User.FindFirst(ClaimConst.CLAINM_SUPERADMIN)?.Value == "1";
  73. }
  74. }
  75. }