-
Notifications
You must be signed in to change notification settings - Fork 1.3k
b1.Aop‐SQL events
果糖网 edited this page Jul 21, 2024
·
3 revisions
Note: Aop must be set before you manipulate the statement, otherwise it won't work, and it must be the same SqlSuagrClient
public SqlSugarClient GetInstance()
{
SqlSugarClient Db= new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = "Server=.xxxxx",
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
},db=>{
// If it is multi-library look at title 6
// Events before each Sql execution
db.Aop.OnLogExecuting = (sql, pars) =>
{
// I can write logic in this
// Tip: Get IOC objects in AOP
//var serviceBuilder = services.BuildServiceProvider();
//var log= serviceBuilder.GetService<ILogger<WeatherForecastController>>();
};
//Multiple databases
//db.GetConnection("id").Aop.OnLogExecuting
});
return db;
}
var db=GetInstance();
db.Queryable<T>().ToList(); // The operation will enter an event
//SQL execution is complete
db.Aop.OnLogExecuted = (sql, pars) =>
{
// After execution, you can output the SQL execution time (OnLogExecutedDelegate)
Console.Write("time:" + db.Ado.SqlExecutionTime.ToString());
};
db.Aop.OnLogExecuting = (sql, pars) => // Before the SQL execution
{
// Obtain native SQL recommended 5.1.4.63 Performance OK
//UtilMethods.GetNativeSql(sql,pars)
// Getting parameterized SQL affects performance only suitable for debugging
//UtilMethods.GetSqlString(DbType.SqlServer,sql,pars)
};
db.Aop.OnError = (exp) =>// An SQL error is reported
{
// Obtain native SQL recommended 5.1.4.63 Performance OK
//UtilMethods.GetNativeSql(exp.sql,exp.parameters)
// Obtaining parameterless SQL has an impact on performance, especially large SQL parameters, debugging use
//UtilMethods.GetSqlString(DbType.SqlServer,exp.sql,exp.parameters)
};
Db. Aop. OnExecutingChangeSql = (SQL, pars) = > / / can modify the SQL and parameter values
{
//sql=newsql
//foreach(var p in pars) // Modify
return new KeyValuePair<string, SugarParameter[]>(sql,pars);
};