|
-
- using BPA.SAAS.KitChenManage.Core;
- using BPA.SAAS.Manage.Core.Base;
- using Furion;
- using SqlSugar;
- using System;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Reflection;
-
- namespace BPA.KitChen.GroupMeal.SqlSugar
- {
- public class SqlSugarDb
- {
-
-
-
- public static SqlSugarScope Db { get; set; }
- public static SqlSugarScope DbLog { get; set; }
-
- public static SqlSugarScope SqlSugarScope(ConnectionConfig configConnection)
- {
- //全局过滤
-
- Db = new SqlSugarScope(configConnection, db =>
- {
- //全局过滤
- TableFilterItem(db);
- db.Aop.OnLogExecuting = (sql, pars) =>
- {
- //sql 执行前
- };
- db.Aop.OnLogExecuted = (sql, pars) =>
- {
- Console.WriteLine($"当前SQL语句:【{sql}】,参数:【{string.Join(",", pars.Select(t => t.Value))}】");
- //sql 执行后
- };
- db.Aop.OnError = ex =>
- {
- //sql 异常
- };
- });
-
- return Db;
- }
-
- public static SqlSugarScope SqlSugarScopeLog(ConnectionConfig configConnection)
- {
- //全局过滤
-
- DbLog = new SqlSugarScope(configConnection, db =>
- {
- //全局过滤
- TableFilterItem(db);
- db.Aop.OnLogExecuting = (sql, pars) =>
- {
- //sql 执行前
- };
- db.Aop.OnLogExecuted = (sql, pars) =>
- {
- //sql 执行后
- };
- db.Aop.OnError = ex =>
- {
- //sql 异常
- };
- });
-
- return Db;
- }
-
- #region 全局过滤器及配置
- /// <summary>
- /// 全局过滤
- /// </summary>
- private static void TableFilterItem(SqlSugarClient db)
- {
-
- //添加默认值
- DataExecuting(db);
- db.QueryFilter.AddTableFilter<IGroupId>(it => it.GroupId == CurrentUser.GroupId);
- }
-
- /// <summary>
- /// 附默认值
- /// </summary>
- /// <param name="db"></param>
- private static void DataExecuting(SqlSugarClient db)
- {
- //全局字段赋值
- db.Aop.DataExecuting = (oldValue, entityInfo) =>
- {
- InsertByObject(entityInfo);
- UpdateByObject(oldValue, entityInfo);
- };
-
- }
- /// <summary>
- ///插入数据时附默认值
- /// </summary>
- /// <param name="entityInfo"></param>
- private static void InsertByObject(DataFilterModel entityInfo)
- {
- if (entityInfo.OperationType != DataFilterType.InsertByObject) return;
- switch (entityInfo.PropertyName)
- {
- case "CreateAt":
- entityInfo.SetValue(DateTime.Now);
- break;
- case "CreateBy":
- entityInfo.SetValue("");
- break;
- case "GroupId":
- entityInfo.SetValue(CurrentUser.GroupId);
- break;
- }
- }
-
- /// <summary>
- /// 修改数据时附默认值
- /// </summary>
- /// <param name="oldValue"></param>
- /// <param name="entityInfo"></param>
- private static void UpdateByObject(object oldValue, DataFilterModel entityInfo)
- {
- if (entityInfo.OperationType != DataFilterType.UpdateByObject) return;
-
- switch (entityInfo.PropertyName)
- {
- case "UpdateAt":
- entityInfo.SetValue(DateTime.Now);
- break;
- case "UpdateBy":
- entityInfo.SetValue("");
- break;
- }
-
- }
- #endregion
- }
- }
|