Files
QYZH.InteractiveMagazine/QYZH.InteractiveMagazine.Repository/Core/SqlSugarManager.cs

52 lines
2.0 KiB
C#
Raw Normal View History

using Microsoft.AspNetCore.Builder;
using QYZH.InteractiveMagazine.Repository.Core;
using Serilog;
using SqlSugar;
using SqlSugar.IOC;
namespace QYZH.InteractiveMagazine.Repository.Core
{
/// <summary>
/// sql sugar 管理器
/// </summary>
public static class SqlSugarManager
{
/// <summary>
/// 获基础信息库对象 用IOC这块代码不能写到IOC里面
/// </summary>
public static void InitSqlSugarDb(this WebApplicationBuilder builder, IocConfig config)
{
builder.Services.AddSqlSugar(config);
//配置参数
SugarIocServices.ConfigurationSugar(db =>
{
db.Aop.OnLogExecuting = (sql, pars) =>
{
//var param = db.GetConnectionScope(0).Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value));
Log.Information($"【sql语句】{UtilMethods.GetSqlString((DbType)config.DbType, sql, pars)}\n");
};
db.Aop.OnError = (ex) =>
{
string sql = $"【错误SQL】{UtilMethods.GetSqlString((DbType)config.DbType, ex.Sql, (SugarParameter[])ex.Parametres)}\r\n";
Log.Error(ex, $"{sql}\r\n{ex.Message}\r\n{ex.StackTrace}");
};
//SQL执行完
db.Aop.OnLogExecuted = (sql, pars) =>
{
//执行完了可以输出SQL执行时间 (OnLogExecutedDelegate)
};
db.SetDefaultValue().SetQueryFilter(GetAssemblyNames());//.CreateClassFile("C:\\Model");
});
}
private static string GetAssemblyNames()
{
string friendlyName = AppDomain.CurrentDomain.FriendlyName;
string[] source = friendlyName.Split('.');
string assemblyNames = string.Join(".", source.Take(source.Count() - 1)) + ".Models";
return assemblyNames;
}
}
}