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

196 lines
8.6 KiB
C#

using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Reflection;
using DS.Module.Core;
using DS.Module.Core.Data;
2 years ago
using DS.Module.Core.Extensions;
using DS.Module.User;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
2 years ago
using NLog;
using SqlSugar;
using SqlSugar.Extensions;
2 years ago
using LogLevel = NLog.LogLevel;
namespace DS.Module.SqlSugar;
/// <summary>
/// SqlSugar 启动服务
/// </summary>
public static class SqlsugarInstall
{
// /// <summary>
// /// 数据库连接字符串
// /// </summary>
// private static string DbInfo = AppSetting.Configuration["ConnectionStrings:DbInfo"];
//
// /// <summary>
// /// 数据库类型
// /// </summary>
// private static string DbType = AppSetting.Configuration["ConnectionStrings:DbType"];
2 years ago
static readonly Logger Logger = LogManager.GetCurrentClassLogger();
// private readonly IUser user;
// private ILogger<SqlsugarInstall> _logger;
/// <summary>
/// 将模块服务添加到依赖注入服务容器中
/// </summary>
/// <param name="services">依赖注入服务容器</param>
/// <returns></returns>
public static IServiceCollection AddSqlsugarInstall(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
var dbs = AppSetting.app<DbConfig>( "DBInfo", "DBS");
//默认数据库
List<DbConfig> dbList = new List<DbConfig>();
DbConfig defaultdb = new DbConfig()
{
ConnId = AppSetting.app(new string[] { "DBInfo", "DefaultDbConnId" }),
Connection = AppSetting.app(new string[] { "DBInfo", "DefaultDbString" }),
DbType = AppSetting.app(new string[] { "DBInfo", "DefaultDbType" }).ObjToInt()
};
dbList.Add(defaultdb);
//业务数据库集合
foreach (var item in dbs)
{
dbList.Add(item);
}
List<ConnectionConfig> connectConfigList = new List<ConnectionConfig>();
foreach (var item in dbList)
{
//防止数据库重复,导致的事务异常
if (connectConfigList.Any(a => a.ConfigId == (dynamic)item.ConnId || a.ConnectionString == item.Connection))
{
continue;
}
connectConfigList.Add(new ConnectionConfig()
2 years ago
{
ConnectionString = item.Connection,
DbType = (DbType)item.DbType,
2 years ago
IsAutoCloseConnection = true,
ConfigId = item.ConnId,
2 years ago
InitKeyType = InitKeyType.Attribute,
MoreSettings = new ConnMoreSettings()
{
IsAutoRemoveDataCache = true //自动清理缓存
},
// 自定义特性
ConfigureExternalServices = new ConfigureExternalServices()
{
}
});
}
//全局上下文生效
SqlSugarScope sqlSugar = new SqlSugarScope(connectConfigList,
2 years ago
db =>
{
/*
* /
*/
foreach (var c in connectConfigList)
2 years ago
{
var dbProvider = db.GetConnectionScope((string)c.ConfigId);
var user = services.GetService<IUser>();
//单例参数配置,所有上下文生效
dbProvider.Ado.CommandTimeOut = 30;
dbProvider.Aop.OnLogExecuting = (sql, pars) =>
{
Logger.Log(LogLevel.Info,
DateTime.Now.ToString() + "\r\n" +
UtilMethods.GetSqlString(c.DbType, sql, pars));
};
dbProvider.Aop.DataExecuting = (oldValue, entityInfo) =>
2 years ago
{
// 新增操作
if (entityInfo.OperationType == DataFilterType.InsertByObject)
2 years ago
{
if (entityInfo.PropertyName == "Id")
2 years ago
{
if (entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(string))
{
entityInfo.SetValue(GuidHelper.GetSnowflakeId());
}
2 years ago
}
if (entityInfo.PropertyName == "AddTime")
entityInfo.SetValue(DateTime.Now);
2 years ago
if (!user.GetTenantId().ToString().IsNullOrEmpty())
{
if (entityInfo.PropertyName == "TenantId")
entityInfo.SetValue(user.GetTenantId());
}
// if (entityInfo.PropertyName == "TenantId")
// entityInfo.SetValue(user.GetTenantId());
if (entityInfo.PropertyName == "AddBy")
entityInfo.SetValue(user.UserId);
if (entityInfo.PropertyName == "Deleted")
entityInfo.SetValue(false);
2 years ago
}
// 更新操作
if (entityInfo.OperationType == DataFilterType.UpdateByObject)
{
if (entityInfo.PropertyName == "UpdateTime")
entityInfo.SetValue(DateTime.Now);
if (entityInfo.PropertyName == "UpdateBy")
entityInfo.SetValue(user.UserId);
}
};
dbProvider.Aop.OnError = (exp) => //执行SQL 错误事件
2 years ago
{
Logger.Error(DateTime.Now.ToString() + "\r\n" + exp.Sql + "\r\n" + exp.Parametres);
};
var basePath = AppContext.BaseDirectory;
var servicesDllFile = Path.Combine(basePath, "DS.WMS.Core.dll");
//从程序集拿到实体type集合
Type[] types = Assembly
.LoadFrom(servicesDllFile) //如果 .dll报错可以换成 xxx.exe 有些生成的是exe
.GetTypes().Where(it => it.FullName.Contains("DS.WMS.Core.")) //命名空间过滤,当然你也可以写其他条件过滤
.ToArray(); //断点调试一下是不是需要的Type不是需要的在进行过滤
//全局过滤器
// var superAdminViewAllData = Convert.ToBoolean(App.GetOptions<SystemSettingsOptions>().SuperAdminViewAllData);
foreach (var entityType in types)
{
// 配置多租户全局过滤器
if (!entityType.GetProperty("TenantId").IsNull())
{
//判断实体类中包含TenantId属性
//构建动态Lambda
var lambda = DynamicExpressionParser.ParseLambda
(new[] { Expression.Parameter(entityType, "it") },
typeof(bool), $"{nameof(DBEntityTenant.TenantId)} == @0 ",
user.GetTenantId());
dbProvider.QueryFilter.Add(new TableFilterItem<object>(entityType, lambda)); //将Lambda传入过滤器
}
// // 配置加删除全局过滤器
if (!entityType.GetProperty("Deleted").IsNull())
{ //判断实体类中包含IsDeleted属性
//构建动态Lambda
var lambda = DynamicExpressionParser.ParseLambda
(new[] { Expression.Parameter(entityType, "it") },
typeof(bool), $"{nameof(EntityBase.Deleted)} == @0",
false);
db.QueryFilter.Add(new TableFilterItem<object>(entityType, lambda)
{
IsJoinQuery = true
}); //将Lambda传入过滤器
}
2 years ago
}
}
2 years ago
});
services.AddSingleton<ISqlSugarClient>(sqlSugar); //这边是SqlSugarScope用AddSingleton
return services;
}
}