Files
IOT/ORM/SqlSugarContext.cs
2026-01-14 11:22:58 +08:00

124 lines
4.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Logger;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ORM
{
public class SqlSugarContext
{
/// <summary>
/// SqlSugarScope单例模式
/// </summary>
public static readonly SqlSugarScope DbContext = new SqlSugarScope(
new ConnectionConfig()
{
DbType = DatabaseConfig.DbConnectionType,
ConnectionString = DatabaseConfig.DbConnectionString, // 连接符字串
//ConfigId = "Db1",//管理多个数据库
IsAutoCloseConnection = true, // 自动关闭连接
InitKeyType = InitKeyType.Attribute // 通过实体类上的特性初始化
},
db =>
{
// 执行超时时间,单位秒
db.Ado.CommandTimeOut = 30;
// 每次SQL执行前事件
db.Aop.OnLogExecuting = (sql, pars) =>
{
#if DEBUG
// 确保 SQL 只通过 sqlLogger 记录
LoggerHelper.sqlLogger.Info("Executing SQL: {0} with parameters: {1}", sql, pars); // 使用 NLog 记录 SQL
#endif
};
// SQL执行完
db.Aop.OnLogExecuted = (sql, pars) =>
{
// 执行时间超过1秒记录慢日志
if (db.Ado.SqlExecutionTime.TotalSeconds > 1)
{
LoggerHelper.sqlLogger.Warn("SQL Slow Execution. Time: {0}, File: {1}, Line: {2}, Method: {3}, SQL: {4}",
db.Ado.SqlExecutionTime.ToString(), // SQL 执行时间
db.Ado.SqlStackTrace.FirstFileName, // 代码 CS 文件名
db.Ado.SqlStackTrace.FirstLine, // 代码行数
db.Ado.SqlStackTrace.FirstMethodName, // 代码方法名
sql); // 使用 NLog 记录慢 SQL 日志
}
};
// SQL 报错
db.Aop.OnError = (exp) =>
{
// 确保 SQL 错误日志仅通过 sqlLogger 记录
LoggerHelper.sqlLogger.Error(exp, "SQL Error: {0}", exp.Sql); // 使用 NLog 记录 SQL 错误日志
};
// 数据过滤器:例如在新增数据时生成雪花 Id
db.Aop.DataExecuting = (oldValue, entityInfo) =>
{
// 新增操作
if (entityInfo.OperationType == DataFilterType.InsertByObject)
{
// 主键(long)赋值雪花 Id
if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
{
var id = ((dynamic)entityInfo.EntityValue).Id;
if (id == null || id == 0)
{
SnowFlakeSingle.WorkId = DatabaseConfig.SnowFlakeWorkId;
SnowFlakeSingle.DatacenterId = DatabaseConfig.SnowFlakeDatacenterId;
entityInfo.SetValue(SnowFlakeSingle.Instance.NextId());
}
}
}
};
}
);
/// <summary>
/// 初始化数据库,创建所有后缀为 Entity 的表
/// </summary>
public static void InitDatabase()
{
// 加载 Model.dll 文件
string modelDllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Model.dll");
if (!File.Exists(modelDllPath))
{
throw new FileNotFoundException($"未找到 Model.dll 文件: {modelDllPath}");
}
// 加载指定的程序集Model.dll
var modelAssembly = Assembly.LoadFrom(modelDllPath);
// 获取所有的 Model层下的Entity 类(后缀为 Entity
var entityTypes = modelAssembly.GetTypes()
.Where(t => t.Name.EndsWith("Entity") && t.IsClass && !t.IsInterface && !t.IsAbstract)
.ToList();
// 使用 SqlSugar 自动创建表
using (var db = DbContext)
{
foreach (var entityType in entityTypes)
{
// 判断该类型是否为类且符合条件
if (entityType.IsClass)
{
// 自动创建表
db.CodeFirst.InitTables(entityType);
}
}
}
}
}
}