using BPA.SAAS.KitChenManage.Comm.Const; using BPA.SAAS.KitChenManage.Core.Base; using Furion; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using SqlSugar; using System; using System.Collections.Generic; using System.Data; using System.Linq; namespace BPA.SAAS.KitChenManage.Core { /// /// 数据库上下文对象 /// public static class DbContext { /// /// SqlSugar 数据库实例 /// public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration) { var connectionConfigs = App.GetConfig>("ConnectionConfigs"); //如果多个数数据库传 List var configConnection = new ConnectionConfig() { ConnectionString = connectionConfigs[0].ConnectionString, DbType = SqlSugar.DbType.MySql,//设置数据库类型 IsAutoCloseConnection = true,//自动释放数据务,如果存在事务,在事务结束后释放 InitKeyType = InitKeyType.Attribute, //从实体特性中读取主键自增列信息 ConfigId = "default", }; SqlSugarScope sqlSugar = new SqlSugarScope(configConnection, db => { //过滤已删除数据 db.QueryFilter.AddTableFilter(it => it.IsDeleted == 0); //db.QueryFilter.AddTableFilter(it => it.Status == 0); if (App.User.FindFirst(ClaimConst.CLAINM_SUPERADMIN)?.Value != null) { //非管理员账户过滤加盟商数据 var groupId = App.User?.FindFirst(ClaimConst.GroupId)?.Value; db.QueryFilter.AddTableFilter(it => it.GroupId == groupId); } db.Aop.DataExecuting = (oldValue, entityInfo) => { //新增添加加盟商id赋值 var groupId = App.User?.FindFirst(ClaimConst.GroupId)?.Value; if (entityInfo.PropertyName == "GroupId" && entityInfo.OperationType == DataFilterType.InsertByObject) { if (oldValue == null || oldValue == Convert.DBNull) { entityInfo.SetValue(groupId); } } }; //单例参数配置,所有上下文生效 db.Aop.OnLogExecuting = (sql, pars) => { //Console.WriteLine(sql);//输出sql Console.WriteLine($"当前SQL语句:【{sql}】,参数:【{string.Join(",", pars.Select(t => t.Value))}】"); }; }); services.AddSingleton(sqlSugar);//这边是SqlSugarScope用AddSingleton } // /// 判断是不是超级管理员 /// /// private static bool IsSuperAdmin() { if (App.User == null) return false; return App.User.FindFirst(ClaimConst.CLAINM_SUPERADMIN)?.Value == "1"; } } }