using BPA.KitChen.GroupMealOrder.Core;
using BPA.KitChen.GroupMealOrder.Core.Common;
using BPA.KitChen.GroupMealOrder.Core.Common.Const;
using BPA.KitChen.GroupMealOrder.Core.Entity.Base;
using Furion;
using Furion.DatabaseAccessor;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace BPA.KitChen.GroupMealOrder.SqlSugar
{
public class SqlSugarDb
{
public static SqlSugarScope Db { get; set; }
public static SqlSugarScope SqlSugarScope(ConnectionConfig configConnection)
{
//全局过滤
Db = new SqlSugarScope(configConnection, db =>
{
//全局过滤
TableFilterItem(db);
db.Aop.OnLogExecuting = (sql, pars) =>
{
Console.WriteLine(sql);
//sql 执行前
};
db.Aop.OnLogExecuted = (sql, pars) =>
{
//sql 执行后
};
db.Aop.OnError = ex =>
{
//sql 异常
};
});
return Db;
}
#region 全局过滤器及配置
///
/// 全局过滤
///
private static void TableFilterItem(SqlSugarClient db)
{
//添加默认值
DataExecuting(db);
//// 配置租户过滤器
//var tenantId = App.User?.FindFirst(ClaimConst.GroupId)?.Value;
//db.QueryFilter.AddTableFilter(u => u.GroupId == tenantId);
//db.QueryFilter.AddTableFilter(u => u.IsDeleted ==0);
var types = Assembly.Load("BPA.KitChen.GroupMealOrder.Core").GetTypes()
.Where(x => x.GetCustomAttribute() != null);
foreach (var entityType in types)
{
if (entityType.GetProperty("GroupId") != null)//判断实体类中包含属性
{
var groupId = string.IsNullOrWhiteSpace(CurrentUser.TenantId)
? App.User?.FindFirst(ClaimConst.GroupId)?.Value
: CurrentUser.TenantId;
//构建动态Lambda
var lambda = DynamicExpressionParser.ParseLambda
(new[] { Expression.Parameter(entityType, "it") },
typeof(bool), $"{nameof(IBaseGroupIdEntity.GroupId)} == @0",
groupId);
db.QueryFilter.Add(new TableFilterItem