using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using SqlSugar; namespace HH.WCS.Mobox3.DSZSH.util { //DOC:https://www.donet5.com/Home/Doc //NOTE:如果用Oracle数据库,需要包Oracle.ManagedDataAccess/21.15.0,环境netframework/4.6.2(太新了4.8,有的服务器安装不上去) //NOTE:SqlHelper带T的原因,是旧框架编写了`Update(T model, string[] cols)`等代码(参考HH-0014_NongFu_QingXi 农夫青溪) public class SqlHelper where T : class, new() { public SqlSugarClient GetInstance() { //创建数据库对象 SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = Settings.DbConn, DbType = Settings.DbType, IsAutoCloseConnection = true, InitKeyType = InitKeyType.Attribute//从特性读取主键自增信息 }); //监控所有超过1秒的Sql db.Aop.OnLogExecuted = (sql, p) => { //执行时间超过1秒 if (db.Ado.SqlExecutionTime.TotalSeconds > 1) { Console.WriteLine(sql + "\r\n" + db.Utilities.SerializeObject(p.ToDictionary(it => it.ParameterName, it => it.Value))); //代码CS文件名 var fileName = db.Ado.SqlStackTrace.FirstFileName; //代码行数 var fileLine = db.Ado.SqlStackTrace.FirstLine; //方法名 var FirstMethodName = db.Ado.SqlStackTrace.FirstMethodName; } //相当于EF的 PrintToMiniProfiler }; //配置AOP日志 //db.Aop.OnLogExecuting = (sql, pars) => //{ // Console.WriteLine(sql);//输出纯SQL语句 //}; //每次设置数值时都去除前导后导空格 db.Aop.DataExecuted = (value, entity) => { entity.EntityColumnInfos.ToList().ForEach(a => { var pvalue = entity.GetValue(a.PropertyName); if (pvalue != null && pvalue.GetType() == typeof(String)) { entity.SetValue(a.PropertyName, pvalue.ToString().Trim()); } }); }; //设置AOP中的事件处理程序 //db.Aop.OnExecutingChangeSql = (sql, p) => { // // 示例:自动过滤软删除数据 // if (sql.StartsWith("SELECT")) { // sql += " WHERE IsDeleted = 0"; // } // return new KeyValuePair(sql, p); //}; return db; } } }