当前位置:网站首页>Sqlsugar help class
Sqlsugar help class
2022-06-09 19:43:00 【Crazy programmer】
SqlsugarHelper
public class SqlsugarHelper
{
static string ConnectionString = string.Empty;
static SqlSugar.DbType dbtype = SqlSugar.DbType.SqlServer;
SqlsugarHelper( SqlSugar.DbType dbtype)
{
if(dbtype== SqlSugar.DbType.SqlServer)
{
SqlsugarHelper.ConnectionString = ConnTools.init().GetSqlServerConn();
}else if(dbtype == SqlSugar.DbType.Oracle)
{
SqlsugarHelper.ConnectionString = ConnTools.init().GetOracleConn();
}
SqlsugarHelper.dbtype = dbtype;
}
private static SqlsugarHelper _Singleton = null;
private static object Singleton_Lock = new object();
public static SqlsugarHelper Init(SqlSugar.DbType dbtype= SqlSugar.DbType.SqlServer)
{
if (_Singleton == null) // double if +lock
{
lock (Singleton_Lock)
{
if (_Singleton == null)
{
// Create objects
_Singleton = new SqlsugarHelper(dbtype);
}
}
}
return _Singleton;
}
/// <summary>
/// Get database connection entity , Static variable docking is prohibited
/// </summary>
public static SqlSugarClient Instance
{
get
{
if (!string.IsNullOrWhiteSpace(ConnectionString))
{
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = ConnectionString,
DbType = dbtype,// Set database type
IsAutoCloseConnection = true,// Automatically release data , If there is a transaction , Release... After the transaction ends
InitKeyType = InitKeyType.SystemTable,// Read the primary key information from the database system table (InitKeyType.Attribute Read the self incrementing information of the primary key from the entity properties )
});
// debugging SQL,AOP , journal
db.Aop.OnLogExecuted = (sql, pars) => //SQL After executing the event
{
#if DEBUG
// Get the total number of milliseconds after execution
double sqlExecutionTotalMilliseconds = db.Ado.SqlExecutionTime.TotalMilliseconds;
#endif
};
db.Aop.OnLogExecuting = (sql, pars) => //SQL Event before execution . The generated... Can be viewed here sql
{
#if DEBUG
string tempSQL = LookSQL(sql, pars);
#endif
};
db.Aop.OnError = (exp) =>// perform SQL Error events
{
//exp.sql exp.parameters You can get the parameters and errors Sql
StringBuilder sb_SugarParameterStr = new StringBuilder("###SugarParameter Parameter is :");
var parametres = exp.Parametres as SugarParameter[];
if (parametres != null)
{
sb_SugarParameterStr.Append(JsonConvert.SerializeObject(parametres));
}
StringBuilder sb_error = new StringBuilder();
sb_error.AppendLine("SqlSugarClient perform sql Abnormal information :" + exp.Message);
sb_error.AppendLine("### After the assignment sql:" + LookSQL(exp.Sql, parametres));
sb_error.AppendLine("### Parameterized sql:" + exp.Sql);
sb_error.AppendLine("### parameter information :" + sb_SugarParameterStr.ToString());
sb_error.AppendLine("###StackTrace Information :" + exp.StackTrace);
};
db.Aop.OnExecutingChangeSql = (sql, pars) => //SQL Before execution You can modify SQL
{
// Judge update or delete Whether the method has where Conditions . If you really want to delete all the data , please where(p=>true) or where(p=>p.id>0)
if (sql.TrimStart().IndexOf("delete ", StringComparison.CurrentCultureIgnoreCase) == 0)
{
if (sql.IndexOf("where", StringComparison.CurrentCultureIgnoreCase) <= 0)
{
throw new Exception("delete The deletion method needs to have where Conditions !!");
}
}
else if (sql.TrimStart().IndexOf("update ", StringComparison.CurrentCultureIgnoreCase) == 0)
{
if (sql.IndexOf("where", StringComparison.CurrentCultureIgnoreCase) <= 0)
{
throw new Exception("update The update method needs to have where Conditions !!");
}
}
return new KeyValuePair<string, SugarParameter[]>(sql, pars);
};
//db.Aop.OnDiffLogEvent = it =>// Data changes before and after database operation .
//{
// var editBeforeData = it.BeforeData;
// var editAfterData = it.AfterData;
// var sql = it.Sql;
// var parameter = it.Parameters;
// var data = it.BusinessData;
// var time = it.Time;
// var diffType = it.DiffType;// Enumerated values insert 、update and delete Used for business differentiation
// // You can write the log method here
//};
//db.Ado.CommandTimeOut // Set up sql Execution timeout waiting time ( Millisecond unit )
//db.Ado.Connection.ConnectionTimeout // Set the database connection wait time ( Millisecond unit )
return db;
}
else
{
return null;
}
}
}
/// <summary>
/// View the assigned sql
/// </summary>
/// <param name="sql"></param>
/// <param name="pars"> Parameters </param>
/// <returns></returns>
private static string LookSQL(string sql, SugarParameter[] pars)
{
if (pars == null || pars.Length == 0) return sql;
StringBuilder sb_sql = new StringBuilder(sql);
var tempOrderPars = pars.Where(p => p.Value != null).OrderByDescending(p => p.ParameterName.Length).ToList();// prevent @par1 Error replacement @par12
for (var index = 0; index < tempOrderPars.Count; index++)
{
sb_sql.Replace(tempOrderPars[index].ParameterName, "'" + tempOrderPars[index].Value.ToString() + "'");
}
return sb_sql.ToString();
}
#region Get entities
/// <summary>
/// Get an entity
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="id"> Primary key </param>
/// <returns></returns>
public T GetModel<T>(object id)
{
return GetModel<T>(id, SqlsugarHelper.Instance);
}
/// <summary>
/// Get an entity
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="id"> Primary key </param>
/// <param name="TableName"> The name of the table </param>
/// <returns></returns>
public T GetModel<T>(object id,string TableName)
{
return GetModel<T>(id, TableName, SqlsugarHelper.Instance);
}
/// <summary>
/// Get multiple entities
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="id"> Primary key </param>
/// <returns></returns>
public List<T> GetModelList<T>()
{
return GetModelList<T>(SqlsugarHelper.Instance);
}
/// <summary>
/// Get multiple entities
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="id"> Primary key </param>
/// <param name="TableName"> The name of the table </param>
/// <returns></returns>
public List<T> GetModelList<T>(string TableName)
{
return GetModelList<T>(SqlsugarHelper.Instance,TableName);
}
/// <summary>
/// Get an entity
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="id"> Primary key </param>
/// <param name="db"></param>
/// <returns></returns>
public T GetModel<T>(object id, SqlSugarClient db)
{
return db.Queryable<T>().InSingle(id);
}
/// <summary>
/// Get an entity
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="id"> Primary key </param>
/// <param name="db"></param>
/// <returns></returns>
public T GetModel<T>(object id,string
TableName, SqlSugarClient db)
{
return db.Queryable<T>().AS(TableName).InSingle(id);
}
/// <summary>
/// Get multiple entities
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="id"> Primary key </param>
/// <param name="db"></param>
/// <returns></returns>
public List<T> GetModelList<T>(SqlSugarClient db)
{
return db.Queryable<T>().ToList();
}
/// <summary>
/// Get multiple entities
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="id"> Primary key </param>
/// <param name="db"></param>
/// <returns></returns>
public List<T> GetModelList<T>(SqlSugarClient db,string TableName)
{
return db.Queryable<T>().AS(TableName).ToList();
}
#region Get an entity from the cache
/// <summary>
/// Get an entity from the cache
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="id"> Primary key </param>
/// <returns></returns>
public T GetModel_WithCache<T>(object id)
{
return GetModel_WithCache<T>(id, Instance);
}
/// <summary>
/// Get an entity from the cache
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="id"> Primary key </param>
/// <param name="db"></param>
/// <returns></returns>
public T GetModel_WithCache<T>(object id, SqlSugarClient db)
{
return db.Queryable<T>().WithCache().InSingle(id);
}
#endregion
#endregion
#region add to
/// <summary>
/// Add entities ( The inconsistency between entity name and table name is caused by )
/// </summary>
/// <typeparam name="T"> Entity type </typeparam>
/// <param name="t"> Entity </param>
/// <param name="TableName"> The name of the table </param>
/// <returns> Returns the number of successfully added entries </returns>
public int InsertModel<T>(T t, string TableName) where T : class, new()
{
return InsertModel(t, TableName, SqlsugarHelper.Instance);
}
/// <summary>
/// Add entities ( The inconsistency between entity name and table name is caused by )
/// </summary>
/// <typeparam name="T"> Entity type </typeparam>
/// <param name="t"> Entity </param>
/// <param name="TableName"> The name of the table </param>
/// <param name="db"> Database connection string </param>
/// <returns></returns>
public int InsertModel<T>(T t, string TableName, SqlSugarClient db) where T : class, new()
{
return db.Insertable(t).AS(TableName).ExecuteCommand();
}
/// <summary>
/// Batch data insertion ( Update if any, insert if none )
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="TableName"></param>
/// <returns></returns>
public int BulkCopyModel<T>(List<T> t, string TableName) where T : class, new()
{
return BulkCopyModel(t, TableName, SqlsugarHelper.Instance);
}
/// <summary>
/// Massive data updates ( If yes, update. If not, insert )
/// </summary>
/// <typeparam name="T"> Model </typeparam>
/// <param name="t"> data </param>
/// <param name="TableName"> Table name </param>
/// <param name="db"> Database connection </param>
/// <returns></returns>
public int BulkCopyModel<T>(List<T> t, string TableName, SqlSugarClient db) where T : class, new()
{
var x = db.Storageable<T>(t).As(TableName).ToStorage();
int I = x.BulkCopy();// There is no insertion
int U = x.BulkUpdate();// There are updates
return I + U;
}
/// <summary>
/// Batch data insertion ( Do not check whether the data already exists )
/// </summary>
/// <typeparam name="T"> Model type </typeparam>
/// <param name="t"> Data objects </param>
/// <param name="TableName"> The name of the table </param>
/// <returns> Number of lines affected </returns>
public int BulkInsertModel<T>(List<T> t, string TableName) where T : class, new()
{
return BulkInsertModel(t, TableName);
}
/// <summary>
/// Batch data insertion ( Do not check whether the data already exists )
/// </summary>
/// <typeparam name="T"> Model </typeparam>
/// <param name="t"></param>
/// <param name="TableName"> Table name </param>
/// <param name="db"></param>
/// <returns></returns>
public int BulkInsertModel<T>(List<T> t, string TableName, SqlSugarClient db) where T : class, new()
{
return db.Fastest<T>().AS(TableName).BulkCopy(t);
}
/// <summary>
/// Add entity data , And return the primary key value ( The primary key is auto increment int type id, The entity needs to set the primary key property ( by null Fields are not updated , Be careful model With default values )
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public int InsertModel<T>(T t) where T : class, new()
{
return InsertModel(t, SqlsugarHelper.Instance);
}
/// <summary>
/// Add entity data , And return the primary key value ( The primary key is auto increment int type id, The entity needs to set the primary key property )( by null Fields are not updated , Be careful model With default values )
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="db">( The transaction db object )</param>
/// <returns></returns>
public int InsertModel<T>(T t, SqlSugarClient db) where T : class, new()
{
//Where(true/* Do not insert null Columns of values */,false/* Do not insert primary key value */)
return db.Insertable(t).
//IgnoreColumns(p=>p.Equals("id",StringComparison.InvariantCultureIgnoreCase)).
IgnoreColumns(true, false).ExecuteReturnIdentity();
}
/// <summary>
/// Add entity data , And return the primary key value ( The primary key is auto increment long type id, The entity needs to set the primary key property ( by null Fields are not updated , Be careful model With default values )
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public long InsertModel_BigIdentity<T>(T t) where T : class, new()
{
return InsertModel_BigIdentity(t, SqlsugarHelper.Instance);
}
/// <summary>
/// Add entity data , And return the primary key value ( The primary key is auto increment long type id, The entity needs to set the primary key property )( by null Fields are not updated , Be careful model With default values )
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="db">( The transaction db object )</param>
/// <returns></returns>
public long InsertModel_BigIdentity<T>(T t, SqlSugarClient db) where T : class, new()
{
//Where(true/* Do not insert null Columns of values */,false/* Do not insert primary key value */)
return db.Insertable(t).
//IgnoreColumns(p=>p.Equals("id",StringComparison.InvariantCultureIgnoreCase)).
IgnoreColumns(true, false).ExecuteReturnBigIdentity();
}
#region Delete cache
/// <summary>
/// Add entity data , Delete cache , And return the primary key value ( The primary key is auto increment int type id, The entity needs to set the primary key property ( by null Fields are not updated , Be careful model With default values )
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public int InsertModel_RemoveDataCache<T>(T t) where T : class, new()
{
return InsertModel_RemoveDataCache(t, SqlsugarHelper.Instance);
}
/// <summary>
/// Add entity data , Delete cache , And return the primary key value ( The primary key is auto increment int type id, The entity needs to set the primary key property )( by null Fields are not updated , Be careful model With default values )
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="db">( The transaction db object )</param>
/// <returns></returns>
public int InsertModel_RemoveDataCache<T>(T t, SqlSugarClient db) where T : class, new()
{
//Where(true/* Do not insert null Columns of values */,false/* Do not insert primary key value */)
return db.Insertable(t).
//IgnoreColumns(p=>p.Equals("id",StringComparison.InvariantCultureIgnoreCase)).
IgnoreColumns(true, false).RemoveDataCache().ExecuteReturnIdentity();
}
/// <summary>
/// Add entity data , And return the primary key value ( The primary key is auto increment long type id, The entity needs to set the primary key property ( by null Fields are not updated , Be careful model With default values )
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public long InsertModel_BigIdentity_RemoveDataCache<T>(T t) where T : class, new()
{
return InsertModel_BigIdentity_RemoveDataCache(t, SqlsugarHelper.Instance);
}
/// <summary>
/// Add entity data , And return the primary key value ( The primary key is auto increment long type id, The entity needs to set the primary key property )( by null Fields are not updated , Be careful model With default values )
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="db">( The transaction db object )</param>
/// <returns></returns>
public long InsertModel_BigIdentity_RemoveDataCache<T>(T t, SqlSugarClient db) where T : class, new()
{
//Where(true/* Do not insert null Columns of values */,false/* Do not insert primary key value */)
return db.Insertable(t).
//IgnoreColumns(p=>p.Equals("id",StringComparison.InvariantCultureIgnoreCase)).
IgnoreColumns(true, false).RemoveDataCache().ExecuteReturnBigIdentity();
}
#endregion
#endregion
#region to update
/// <summary>
/// Update the entity according to the primary key ( by null Fields are not updated , Be careful model With default values ), Return the number of affected items ( Entity fields should have primary key characteristics )
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public int UpdateModelByKey<T>(T t, string TableName) where T : class, new()
{
return UpdateModelByKey(t, TableName, SqlsugarHelper.Instance);
}
/// <summary>
/// Update the entity according to the primary key , Return the number of affected items ( Entity fields should have primary key characteristics )
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="db">( The transaction db object )</param>
/// <returns></returns>
public int UpdateModelByKey<T>(T t, string TableName, SqlSugarClient db) where T : class, new()
{
// Field null, Do not update
return db.Updateable(t).AS(TableName).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
}
/// <summary>
/// Update entities based on conditional expressions ( by null Fields are not updated , Be careful model With default values ), Return the number of affected items
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="expressionWhere"> Conditional expression </param>
/// <returns></returns>
public int UpdateModelsIgnoreNull<T>(T t, Expression<Func<T, bool>> expressionWhere) where T : class, new()
{
return UpdateModelsIgnoreNull(t, expressionWhere, SqlsugarHelper.Instance);
}
/// <summary>
/// Update entities based on conditional expressions ( by null Fields are not updated , Be careful model With default values ), Return the number of affected items
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="expressionWhere"> Conditional expression </param>
/// <param name="db">( The transaction db object )</param>
/// <returns></returns>
public int UpdateModelsIgnoreNull<T>(T t, Expression<Func<T, bool>> expressionWhere, SqlSugarClient db) where T : class, new()
{
return db.Updateable(t).IgnoreColumns(ignoreAllNullColumns: true).Where(expressionWhere).ExecuteCommand();
}
/// <summary>
/// Update entities based on conditional expressions ( Specify the columns to update ), Return the number of affected items
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"> Model </param>
/// <param name="TableName"> The name of the table in the database </param>
/// <param name="columns"> Fields that need to be updated </param>
/// <param name="expressionWhere"> Conditional expression </param>
/// <returns></returns>
public int UpdateModels<T>(T t, string TableName, Expression<Func<T, object>> columns, Expression<Func<T, bool>> expressionWhere) where T : class, new()
{
return UpdateModels<T>(t, TableName, columns, expressionWhere, SqlsugarHelper.Instance);
}
/// <summary>
/// Update entities based on conditional expressions ( Specify the columns to update ), Return the number of affected items
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="TableName"> Table names in the database </param>
/// <param name="columns"> Field expression to be updated </param>
/// <param name="expressionWhere"> Conditional expression </param>
/// <param name="db">( The transaction db object )</param>
/// <returns></returns>
public int UpdateModels<T>(T t, string TableName, Expression<Func<T, object>> columns, Expression<Func<T, bool>> expressionWhere, SqlSugarClient db) where T : class, new()
{
return db.Updateable(t).AS(TableName).UpdateColumns(columns).Where(expressionWhere).ExecuteCommand();
}
/// <summary>
/// Dynamic update
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="columns"> Write the field to be updated </param>
/// <param name="expressionWhere">where Conditional expression </param>
/// <returns></returns>
public int Update<T>(Expression<Func<T, T>> columns, Expression<Func<T, bool>> expressionWhere) where T : class, new()
{
return Update<T>(columns, expressionWhere, SqlsugarHelper.Instance);
/* Invoke the sample Update<Entity.SysAdmin>(p => new Entity.SysAdmin { photo = photo, Password = newPwd } ,p => p.ID == sm.id && p.Password == oldPwd) > 0; */
}
/// <summary>
/// Dynamic update
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="columns"> The field to be updated </param>
/// <param name="expressionWhere">where Conditional expression </param>
/// <param name="db"></param>
/// <returns></returns>
public int Update<T>(Expression<Func<T, T>> columns, Expression<Func<T, bool>> expressionWhere, SqlSugarClient db) where T : class, new()
{
return db.Updateable<T>().SetColumns(columns).
//IgnoreColumns(ignoreAllNullColumns: true).// This method cannot be added , There will be “CommandText Property has not been initialized ” abnormal
Where(expressionWhere).ExecuteCommand();
/* Invoke the sample Update<Entity.SysAdmin>(p => new Entity.SysAdmin { photo = photo, Password = newPwd } ,p => p.ID == sm.id && p.Password == oldPwd ,db) > 0; */
}
/// <summary>
/// There are batch updates of primary keys
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="TableName"> The name of the table </param>
/// <param name="whereColumns"> Conditional column </param>
/// <param name="updateColumns"> Update column </param>
/// <returns></returns>
public int BulkUpdata<T>(List<T> t, string TableName, string[] whereColumns = null, string[] updateColumns = null) where T : class, new()
{
return BulkUpdata(t, TableName, whereColumns, updateColumns);
}
/// <summary>
/// There are batch updates of primary keys
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="TableName"> The name of the table </param>
/// <param name="db"> Database connection </param>
/// <param name="whereColumns"> Conditional column </param>
/// <param name="updateColumns"> Update column </param>
/// <returns></returns>
public int BulkUpdata<T>(List<T> t, string TableName, SqlSugarClient db, string[] whereColumns, string[] updateColumns) where T : class, new()
{
return db.Fastest<T>().AS(TableName).BulkUpdate(t, whereColumns, updateColumns);
}
#region Delete cache
/// <summary>
/// Update the entity according to the primary key ( by null Fields are not updated , Be careful model With default values ) And delete the cache , Return the number of affected items ( Entity fields should have primary key characteristics )
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public int UpdateModelByKey_RemoveDataCache<T>(T t) where T : class, new()
{
return UpdateModelByKey_RemoveDataCache(t, SqlsugarHelper.Instance);
}
/// <summary>
/// Update the entity according to the primary key , Return the number of affected items ( Entity fields should have primary key characteristics ) And delete the cache , Return the number of affected items ( Entity fields should have primary key characteristics )
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="db">( The transaction db object )</param>
/// <returns></returns>
public int UpdateModelByKey_RemoveDataCache<T>(T t, SqlSugarClient db) where T : class, new()
{
// Field null, Do not update
return db.Updateable(t).IgnoreColumns(ignoreAllNullColumns: true).RemoveDataCache().ExecuteCommand();
}
/// <summary>
/// Update entities based on conditional expressions ( Specify the columns to update ) And delete the cache , Return the number of affected items
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="columns"></param>
/// <param name="expressionWhere"></param>
/// <returns></returns>
public int UpdateModels_RemoveDataCache<T>(T t, Expression<Func<T, object>> columns, Expression<Func<T, bool>> expressionWhere) where T : class, new()
{
return UpdateModels_RemoveDataCache<T>(t, columns, expressionWhere, Instance);
}
/// <summary>
/// Update entities based on conditional expressions ( Specify the columns to update ) And delete the cache , Return the number of affected items
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="columns"></param>
/// <param name="expressionWhere"> Conditional expression </param>
/// <param name="db">( The transaction db object )</param>
/// <returns></returns>
public int UpdateModels_RemoveDataCache<T>(T t, Expression<Func<T, object>> columns, Expression<Func<T, bool>> expressionWhere, SqlSugarClient db) where T : class, new()
{
return db.Updateable(t).UpdateColumns(columns).Where(expressionWhere).RemoveDataCache().ExecuteCommand();
}
/// <summary>
/// Dynamic update , And delete the cache
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="columns"> Write the field to be updated </param>
/// <param name="expressionWhere">where Conditional expression </param>
/// <returns></returns>
public int Update_RemoveDataCache<T>(Expression<Func<T, T>> columns, Expression<Func<T, bool>> expressionWhere) where T : class, new()
{
return Update_RemoveDataCache<T>(columns, expressionWhere, SqlsugarHelper.Instance);
/* Invoke the sample Update<Entity.SysAdmin>(p => new Entity.SysAdmin { photo = photo, Password = newPwd } ,p => p.ID == sm.id && p.Password == oldPwd) > 0; */
}
/// <summary>
/// Dynamic update , And delete the cache
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="columns"> The field to be updated </param>
/// <param name="expressionWhere">where Conditional expression </param>
/// <param name="db"></param>
/// <returns></returns>
public int Update_RemoveDataCache<T>(Expression<Func<T, T>> columns, Expression<Func<T, bool>> expressionWhere, SqlSugarClient db) where T : class, new()
{
return db.Updateable<T>().SetColumns(columns).
//IgnoreColumns(ignoreAllNullColumns: true).// This method cannot be added , There will be “CommandText Property has not been initialized ” abnormal
Where(expressionWhere).RemoveDataCache().ExecuteCommand();
/* Invoke the sample Update<Entity.SysAdmin>(p => new Entity.SysAdmin { photo = photo, Password = newPwd } ,p => p.ID == sm.id && p.Password == oldPwd ,db) > 0; */
}
#endregion
#endregion
#region Delete method
/// <summary>
/// Delete ids String of set condition ( Efficient writing , Be careful to prevent injection attacks )
/// </summary>
/// <param name="ids">ids For the string "1,2,3" or "1" form </param>
/// <param name="key"> Primary key field </param>
/// <returns></returns>
public static bool DeleteByWhereSql_ids<T>(string ids, string key = "id") where T : class, new()
{
return DeleteByWhereSql_ids<T>(ids, SqlsugarHelper.Instance, key);
}
/// <summary>
/// Delete ids String of set condition ( Efficient writing , Be careful to prevent injection attacks )
/// </summary>
/// <param name="ids">ids For the string "1,2,3" or "1" form </param>
/// <param name="db">( The transaction db object )</param>
/// <param name="key"> Primary key field </param>
/// <returns></returns>
public static bool DeleteByWhereSql_ids<T>(string ids, SqlSugarClient db, string key = "id") where T : class, new()
{
return db.Deleteable<T>().Where(string.Format(" {0} IN ({1})", key, ids)).ExecuteCommand() > 0;
}
/// <summary>
/// Delete ids String of set condition
/// </summary>
/// <param name="ids">ids For the string "1,2,3" or "1" form </param>
/// <returns></returns>
public static bool DeleteByIds<T>(string ids) where T : class, new()
{
return DeleteByIds<T>(ids, SqlsugarHelper.Instance);
}
/// <summary>
/// Delete ids String of set condition
/// </summary>
/// <param name="ids">ids For the string "1,2,3" or "1" form </param>
/// <param name="db">( The transaction db object )</param>
/// <returns></returns>
public static bool DeleteByIds<T>(string ids, SqlSugarClient db) where T : class, new()
{
return db.Deleteable<T>(GetIntListByString(ids)).ExecuteCommand() > 0;
}
/// <summary>
/// Delete ids String of set condition
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="ids">ids For the string "1,2,3" or "1" form </param>
/// <returns></returns>
public static bool DeleteByInt64_Ids<T>(string ids) where T : class, new()
{
return DeleteByInt64_Ids<T>(ids, SqlsugarHelper.Instance);
}
/// <summary>
/// Delete ids String of set condition
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="ids">ids For the string "1,2,3" or "1" form </param>
/// <param name="db">( The transaction db object )</param>
/// <returns></returns>
public static bool DeleteByInt64_Ids<T>(string ids, SqlSugarClient db) where T : class, new()
{
return db.Deleteable<T>(GetLongListByString(ids)).ExecuteCommand() > 0;
}
/// <summary>
/// Delete according to the conditional expression , Return the number of affected items
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expression"></param>
/// <returns></returns>
public static int DeleteModels<T>(Expression<Func<T, bool>> expression) where T : class, new()
{
return DeleteModels<T>(expression, SqlsugarHelper.Instance);
}
/// <summary>
/// Delete according to the conditional expression , Return the number of affected items
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expression"> expression </param>
/// <param name="db">( The transaction db object )</param>
/// <returns></returns>
public static int DeleteModels<T>(Expression<Func<T, bool>> expression, SqlSugarClient db) where T : class, new()
{
return db.Deleteable<T>().Where(expression).ExecuteCommand();
}
#region Delete cache
/// <summary>
/// Delete ids String of set condition ( Efficient writing , Be careful to prevent injection attacks ), And delete the cache
/// </summary>
/// <param name="ids">ids For the string "1,2,3" or "1" form </param>
/// <param name="key"> Primary key field </param>
/// <returns></returns>
public static bool DeleteByWhereSql_ids_RemoveDataCache<T>(string ids, string key = "id") where T : class, new()
{
return DeleteByWhereSql_ids_RemoveDataCache<T>(ids, SqlsugarHelper.Instance, key);
}
/// <summary>
/// Delete ids String of set condition ( Efficient writing , Be careful to prevent injection attacks ), And delete the cache
/// </summary>
/// <param name="ids">ids For the string "1,2,3" or "1" form </param>
/// <param name="db">( The transaction db object )</param>
/// <param name="key"> Primary key field </param>
/// <returns></returns>
public static bool DeleteByWhereSql_ids_RemoveDataCache<T>(string ids, SqlSugarClient db, string key = "id") where T : class, new()
{
return db.Deleteable<T>().Where(string.Format(" {0} IN ({1})", key, ids)).RemoveDataCache().ExecuteCommand() > 0;
}
/// <summary>
/// Delete ids String of set condition , And delete the cache
/// </summary>
/// <param name="ids">ids For the string "1,2,3" or "1" form </param>
/// <returns></returns>
public static bool DeleteByIds_RemoveDataCache<T>(string ids) where T : class, new()
{
return DeleteByIds_RemoveDataCache<T>(ids, Instance);
}
/// <summary>
/// Delete ids String of set condition , And delete the cache
/// </summary>
/// <param name="ids">ids For the string "1,2,3" or "1" form </param>
/// <param name="db">( The transaction db object )</param>
/// <returns></returns>
public static bool DeleteByIds_RemoveDataCache<T>(string ids, SqlSugarClient db) where T : class, new()
{
return db.Deleteable<T>(GetIntListByString(ids)).RemoveDataCache().ExecuteCommand() > 0;
}
/// <summary>
/// Delete ids String of set condition , And delete the cache
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="ids">ids For the string "1,2,3" or "1" form </param>
/// <returns></returns>
public static bool DeleteByInt64_Ids_RemoveDataCache<T>(string ids) where T : class, new()
{
return DeleteByInt64_Ids_RemoveDataCache<T>(ids, Instance);
}
/// <summary>
/// Delete ids String of set condition , And delete the cache
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="ids">ids For the string "1,2,3" or "1" form </param>
/// <param name="db">( The transaction db object )</param>
/// <returns></returns>
public static bool DeleteByInt64_Ids_RemoveDataCache<T>(string ids, SqlSugarClient db) where T : class, new()
{
return db.Deleteable<T>(GetLongListByString(ids)).RemoveDataCache().ExecuteCommand() > 0;
}
#endregion
#endregion
#region ids Transition set
/// <summary>
/// Convert string to int Array (, Division of no. )
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public static int[] GetIntListByString(string ids)
{
if (string.IsNullOrWhiteSpace(ids)) return null;
return Array.ConvertAll<string, int>(ids.Split(','), Int32.Parse);
}
/// <summary>
/// Convert string to long Array (, Division of no. )
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public static long[] GetLongListByString(string ids)
{
if (string.IsNullOrWhiteSpace(ids)) return null;
return Array.ConvertAll<string, long>(ids.Split(','), Int64.Parse);
}
#endregion
#region Expanded query , Not recommended
/// <summary>
/// Simple query data
/// </summary>
/// <param name="tableName"> Table name </param>
/// <param name="columns"> Field </param>
/// <param name="dicWhere"> Conditions </param>
/// <returns></returns>
public DataTable GetDataTable(string tableName, string columns, Dictionary<string, object> dicWhere)
{
var db = SqlsugarHelper.Instance;
string sql = string.Format("select {0} from {1} ", columns, tableName);
List<SugarParameter> sqlParams = new List<SugarParameter>();
if (dicWhere != null)
{
string whereSql = dicFill_where(dicWhere, ref sqlParams);
return db.Ado.GetDataTable(sql + " where 1=1 " + whereSql, sqlParams.ToArray());
}
else
{
return db.Ado.GetDataTable(sql);
}
}
/// <summary>
/// Query data
/// </summary>
/// <param name="sqlStr">sql</param>
/// <param name="dicWhere"> Conditions </param>
/// <param name="whereSql">where Conditions , Add and ( Be careful sql Injection attack )</param>
/// <param name="parList"> Extension parameters </param>
/// <returns></returns>
public DataTable GetDataTableBySql(string sqlStr, Dictionary<string, object> dicWhere, string whereSql = "", List<SugarParameter> parList = null)
{
var db = SqlsugarHelper.Instance;
List<SugarParameter> sqlParams = new List<SugarParameter>();
string _whereSql = dicFill_where(dicWhere, ref sqlParams) + whereSql;
if (parList != null && parList.Count > 0)
{
sqlParams.AddRange(parList);
}
if (sqlParams.Count > 0)
{
return db.Ado.GetDataTable(string.Format(sqlStr + " {0} ", " where 1=1 " + _whereSql), sqlParams.ToArray());
}
else
{
return db.Ado.GetDataTable(string.IsNullOrEmpty(whereSql) ? sqlStr : sqlStr + whereSql);
}
}
/// <summary>
/// Query data
/// </summary>
/// <param name="sql">sql sentence </param>
/// <param name="parameters"> Parameters </param>
/// <param name="ConnectionString"> Connection string </param>
/// <param name="dbType"> Database type </param>
/// <returns>Datatable</returns>
public DataTable Query(string sql, List<SugarParameter> parameters)
{
var dt = SqlsugarHelper.Instance.Ado.GetDataTable(sql, parameters);
return dt;
}
/// <summary>
/// Paging data retrieval
/// </summary>
/// <param name="tableName"> The name of the table generated by the front sub query </param>
/// <param name="dicWhere">where Condition field set </param>
/// <param name="whereSql">where Conditions , Add and ( Be careful sql Inject )</param>
/// <param name="orderbyColumn"> Sort field </param>
/// <param name="pageIndex"> The current page number ( from 0 Start )</param>
/// <param name="pageSize"> How many records are displayed on one page </param>
/// <param name="recordCount"> Return the total record </param>
/// <param name="cte">cte Of sql</param>
/// <returns></returns>
public DataTable GetDataPage(string tableName, Dictionary<string, object> dicWhere, string whereSql, string orderbyColumn, int pageIndex, int pageSize, out int recordCount, string cte = "")
{
var db = SqlsugarHelper.Instance;
List<SugarParameter> par = new List<SugarParameter>();
StringBuilder where = new StringBuilder();
where.Append(" where 1=1 ");
where.Append(dicFill_where(dicWhere, ref par) + whereSql);
string tableSql = tableName.Contains("select ") ?
string.Format(" ( " + tableName + " {0} ) pageTable ", where.ToString()) :
string.Format(" ( select * from " + tableName + " {0} ) pageTable ", where.ToString());
string sql = string.Format(@"{5} select {0},row_number() over(order by {1}) rid into #tt from {2} Order By {1} select * from #tt where rid> {3} and rid<={4} ;select count(1) from #tt ;drop table #tt ",
" * ", orderbyColumn, tableSql, pageSize * pageIndex, pageSize * (pageIndex + 1), cte);
DataSet ds = par.Count > 0 ? db.Ado.GetDataSetAll(sql, par.ToArray()) : db.Ado.GetDataSetAll(sql);
recordCount = Convert.ToInt32(ds.Tables[1].Rows[0][0].ToString());
return ds.Tables[0];
}
/// <summary>
/// encapsulation where Parameters sql sentence
/// </summary>
/// <param name="dicWhere"></param>
/// <param name="par"></param>
/// <returns></returns>
private string dicFill_where(Dictionary<string, object> dicWhere, ref List<SugarParameter> par)
{
StringBuilder whereSql = new StringBuilder();
if (dicWhere != null && dicWhere.Count > 0)
{
string keyName;
foreach (KeyValuePair<string, object> keyDic in dicWhere)
{
keyName = getParameterName(keyDic.Key);
if (keyDic.Value.ToString().Contains("%") ||
keyDic.Value.ToString().Contains("_") ||
(keyDic.Value.ToString().Contains("[") && keyDic.Value.ToString().Contains("]"))
) // As long as it contains % _ [ ] Are based on fuzzy queries
{
whereSql.AppendFormat(" and {0} like @{1} ", keyDic.Key, keyName);
}
else
{
whereSql.AppendFormat(" and {0} = @{1} ", keyDic.Key, keyName);
}
par.Add(new SugarParameter(string.Format("@{0}", keyName), keyDic.Value));
}
}
return whereSql.ToString();
}
/// <summary>
/// Put the field name [dbo].[new].[title] , Take the field name title
/// </summary>
/// <param name="key"> Field </param>
/// <returns></returns>
private string getParameterName(string key)
{
var temp = key.Split('.');
StringBuilder sb = new StringBuilder(temp[temp.Length - 1]);
sb.Replace("[", string.Empty).Replace("]", string.Empty);
return sb.ToString();
}
/// <summary>
/// Add data dynamically
/// </summary>
/// <param name="tableName"> Table name </param>
/// <param name="dic"> Set of parameters and corresponding values </param>
/// <returns> Newly added data id</returns>
public int InsertDB(string tableName, Dictionary<string, object> dic)
{
StringBuilder columns = new StringBuilder();
StringBuilder columnParameters = new StringBuilder();
List<SugarParameter> sqlParams = new List<SugarParameter>();
if (dic.Count > 0)
{
foreach (KeyValuePair<string, object> keyDic in dic)
{
columns.AppendFormat(",{0}", keyDic.Key);
columnParameters.AppendFormat(",@{0}", getParameterName(keyDic.Key));
sqlParams.Add(new SugarParameter(string.Format("@{0}", getParameterName(keyDic.Key)), keyDic.Value));
}
}
else
{
return 0;
}
string sql =
string.Format("insert into {0}({1}) values ({2});select @@IDENTITY",
tableName, columns.ToString().Substring(1), columnParameters.ToString().Substring(1));
return SqlsugarHelper.Instance.Ado.ExecuteCommand(sql, sqlParams.ToArray());
}
/// <summary>
/// Update data dynamically
/// </summary>
/// <param name="tableName"> Table name </param>
/// <param name="dic"> Set of parameters and corresponding values </param>
/// <param name="whereSql">where Conditions ( Be careful sql Injection attack )</param>
/// <returns> Whether the update is successful !</returns>
public bool UpdateDB(string tableName, Dictionary<string, object> dic, string whereSql)
{
StringBuilder columns = new StringBuilder();
List<SugarParameter> sqlParams = new List<SugarParameter>();
string keyName;
if (dic != null && dic.Count > 0)
{
foreach (KeyValuePair<string, object> keyDic in dic)
{
keyName = getParameterName(keyDic.Key);
columns.AppendFormat(",{0}[email protected]{1}", keyDic.Key, keyName);
sqlParams.Add(new SugarParameter(string.Format("@{0}", keyName), keyDic.Value));
}
}
else
{
return false;
}
string sql =
string.Format("update {0} set {1} where {2}",
tableName, columns.ToString().Substring(1), whereSql);
return SqlsugarHelper.Instance.Ado.ExecuteCommand(sql, sqlParams) > 0;
}
/// <summary>
/// Update data dynamically
/// </summary>
/// <param name="tableName"> Table name </param>
/// <param name="dic"> Set of parameters and corresponding values </param>
/// <param name="dicWhere">where Set of condition parameters and corresponding values </param>
/// <returns> Whether the update is successful !</returns>
public bool UpdateDB(string tableName, Dictionary<string, object> dic, Dictionary<string, object> dicWhere)
{
StringBuilder columns = new StringBuilder();
StringBuilder wheresSql = new StringBuilder();
List<SugarParameter> sqlParams = new List<SugarParameter>();
string keyName;
if (dic != null && dic.Count > 0)
{
foreach (KeyValuePair<string, object> keyDic in dic)
{
keyName = getParameterName(keyDic.Key);
columns.AppendFormat(",{0}[email protected]{1}", keyDic.Key, keyName);
sqlParams.Add(new SugarParameter(string.Format("@{0}", keyName), keyDic.Value));
}
}
else
{
return false;
}
if (dicWhere != null && dicWhere.Count > 0)
{
foreach (KeyValuePair<string, object> keyDic in dicWhere)
{
keyName = getParameterName(keyDic.Key);
wheresSql.AppendFormat(" and {0}[email protected]{1}", keyDic.Key, keyName);
sqlParams.Add(new SugarParameter(string.Format("@{0}", keyName), keyDic.Value));
}
}
else
{
return false;
}
string sql =
string.Format("update {0} set {1} where 1=1 {2}",
tableName, columns.ToString().Substring(1), wheresSql.ToString().Substring(1));
return SqlsugarHelper.Instance.Ado.ExecuteCommand(sql, sqlParams) > 0;
}
/// <summary>
/// Query whether this record exists
/// </summary>
/// <param name="tableName"> Table name </param>
/// <param name="dicWhere"> Conditions </param>
/// <param name="whereSql"> Conditions ( Add and)</param>
/// <returns></returns>
public bool Exists(string tableName, Dictionary<string, object> dicWhere, string whereSql = "")
{
string sql = string.Format("select count(1) from {0} where 1=1 ", tableName);
List<SugarParameter> sqlParams = new List<SugarParameter>();
string whereSql2 = dicFill_where(dicWhere, ref sqlParams) + whereSql;
return SqlsugarHelper.Instance.Ado.GetInt(sql + whereSql2, sqlParams) > 0;
}
#endregion
}
边栏推荐
- Ziguang zhanrui mobile phone chips are exposed to have serious security vulnerabilities, and about 10% of Android phones in the world may be affected
- More than observation | Alibaba cloud observable Technology Summit officially launched
- STM32内存知识
- WIN7 64位旗舰版安装OFFICE2003 提示:“错误1919,配置ODBC数据源MS Access Database时发生错误ODEC错误”
- 浅谈Go语言反射
- 学习WMX3,运动控制
- Zhaoguan electronics, a visual AI chip manufacturer, obtained a financing of 100 million yuan, led by ICBC capital
- 20XX年全國職業院校技能大賽高職組“信息安全管理與評估”賽項任務書
- mtb12_ PearsonR_ correlAtion coefficient_ heatmap_ Distribution Bin_ Clean step type conversion caution_ spatial dist_ Change para value
- Smart PLC calls the same subroutine (FC) multiple times
猜你喜欢

苹果宣布 2022 年 Apple 设计大奖得主

C语言实现简易计算器

Meinong bio is about to be listed: its operation has been relatively stable in the past three years, and it is estimated that the over raised amount is about 100million yuan

Learn wmx3, motion control

Betting on cloud nativity, ampere computing starts the key shot of server chip transformation

Uniapp H5 single page horizontal screen

2022年全国最新消防设施操作员(高级消防设施操作员)考试题库及答案

What operation and maintenance software and tools will be used for online operation and maintenance?

Troubleshooting cl210openstack operations -- diagnosing openstack problems

使用nvm下载安装Node
随机推荐
2022 XX information security management and evaluation competition
mysql数据类型
Investment of 550million yuan! Merck announced to build an advanced semiconductor integration base in Zhangjiagang, China
odoo 通过ir.model.access.csv修改其它模块权限
SMART PLC多次调用同一个子程序(FC)
2020年“磐云杯”网络空间安全技能竞赛全国拉赛
5 sous - chaîne palindrome la plus longue (intervalle DP)
Betting on cloud nativity, ampere computing starts the key shot of server chip transformation
dump.pcapng数据包解析
Drive development - Basics
【UE5】UObject中调用WorldSubsystem
二零二二年读书计划
Edge浏览器设置网速限制
Description des tâches du concours « gestion et évaluation de la sécurité de l'information » du groupe professionnel supérieur du concours national de compétences des écoles professionnelles en 20xx
《微信小程序-基础篇》初识微信小程序
Learn wmx3, motion control
Node版本切换
What operation and maintenance software and tools will be used for online operation and maintenance?
< collection > and < Association > labels
In the first quarter, 68.2 million TWS earphones were shipped worldwide: Apple ranked first and Xiaomi ranked third