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 readonly object Singleton_Lock = new object();
public static SqlsugarHelper Init(SqlSugar.DbType dbtype= SqlSugar.DbType.SqlServer)
{
if (_Singleton == null)
{
lock (Singleton_Lock)
{
if (_Singleton == null)
{
_Singleton = new SqlsugarHelper(dbtype);
}
}
}
return _Singleton;
}
public static SqlSugarClient Instance
{
get
{
if (!string.IsNullOrWhiteSpace(ConnectionString))
{
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = ConnectionString,
DbType = dbtype,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.SystemTable,
});
db.Aop.OnLogExecuted = (sql, pars) =>
{
#if DEBUG
double sqlExecutionTotalMilliseconds = db.Ado.SqlExecutionTime.TotalMilliseconds;
#endif
};
db.Aop.OnLogExecuting = (sql, pars) =>
{
#if DEBUG
string tempSQL = LookSQL(sql, pars);
#endif
};
db.Aop.OnError = (exp) =>
{
StringBuilder sb_SugarParameterStr = new StringBuilder("###SugarParameter参数为:");
var parametres = exp.Parametres as SugarParameter[];
if (parametres != null)
{
sb_SugarParameterStr.Append(JsonConvert.SerializeObject(parametres));
}
StringBuilder sb_error = new StringBuilder();
sb_error.AppendLine("SqlSugarClient执行sql异常信息:" + exp.Message);
sb_error.AppendLine("###赋值后sql:" + LookSQL(exp.Sql, parametres));
sb_error.AppendLine("###带参数的sql:" + exp.Sql);
sb_error.AppendLine("###参数信息:" + sb_SugarParameterStr.ToString());
sb_error.AppendLine("###StackTrace信息:" + exp.StackTrace);
};
db.Aop.OnExecutingChangeSql = (sql, pars) =>
{
if (sql.TrimStart().IndexOf("delete ", StringComparison.CurrentCultureIgnoreCase) == 0)
{
if (sql.IndexOf("where", StringComparison.CurrentCultureIgnoreCase) <= 0)
{
throw new Exception("delete删除方法需要有where条件!!");
}
}
else if (sql.TrimStart().IndexOf("update", StringComparison.CurrentCultureIgnoreCase) == 0)
{
if (sql.IndexOf("where", StringComparison.CurrentCultureIgnoreCase) <= 0 && sql.IndexOf("on", StringComparison.CurrentCultureIgnoreCase) <= 0)
{
throw new Exception("update更新方法需要有where条件!!");
}
}
return new KeyValuePair<string, SugarParameter[]>(sql, pars);
};
return db;
}
else
{
return null;
}
}
}
public static SqlSugarScope _Instance
{
get
{
if (!string.IsNullOrWhiteSpace(ConnectionString))
{
SqlSugarScope db = new SqlSugarScope(new ConnectionConfig()
{
ConnectionString = ConnectionString,
DbType = dbtype,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.SystemTable,
});
db.Aop.OnLogExecuted = (sql, pars) =>
{
#if DEBUG
double sqlExecutionTotalMilliseconds = db.Ado.SqlExecutionTime.TotalMilliseconds;
#endif
};
db.Aop.OnLogExecuting = (sql, pars) =>
{
#if DEBUG
string tempSQL = LookSQL(sql, pars);
#endif
};
db.Aop.OnError = (exp) =>
{
StringBuilder sb_SugarParameterStr = new StringBuilder("###SugarParameter参数为:");
var parametres = exp.Parametres as SugarParameter[];
if (parametres != null)
{
sb_SugarParameterStr.Append(JsonConvert.SerializeObject(parametres));
}
StringBuilder sb_error = new StringBuilder();
sb_error.AppendLine("SqlSugarClient执行sql异常信息:" + exp.Message);
sb_error.AppendLine("###赋值后sql:" + LookSQL(exp.Sql, parametres));
sb_error.AppendLine("###带参数的sql:" + exp.Sql);
sb_error.AppendLine("###参数信息:" + sb_SugarParameterStr.ToString());
sb_error.AppendLine("###StackTrace信息:" + exp.StackTrace);
};
db.Aop.OnExecutingChangeSql = (sql, pars) =>
{
if (sql.TrimStart().IndexOf("delete ", StringComparison.CurrentCultureIgnoreCase) == 0)
{
if (sql.IndexOf("where", StringComparison.CurrentCultureIgnoreCase) <= 0)
{
throw new Exception("delete删除方法需要有where条件!!");
}
}
else if (sql.TrimStart().IndexOf("update ", StringComparison.CurrentCultureIgnoreCase) == 0)
{
if (sql.IndexOf("where", StringComparison.CurrentCultureIgnoreCase) <= 0 && sql.IndexOf("on", StringComparison.CurrentCultureIgnoreCase) <= 0)
{
throw new Exception("update更新方法需要有where条件!!");
}
}
return new KeyValuePair<string, SugarParameter[]>(sql, pars);
};
return db;
}
else
{
return null;
}
}
}
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();
for (var index = 0; index < tempOrderPars.Count; index++)
{
sb_sql.Replace(tempOrderPars[index].ParameterName, "'" + tempOrderPars[index].Value.ToString() + "'");
}
return sb_sql.ToString();
}
#region 获取实体
public T GetModel<T>(object id)
{
return GetModel<T>(id, SqlsugarHelper.Instance);
}
public SqlSugarClient GetClient()
{
return SqlsugarHelper.Instance;
}
public SqlSugarScope _GetClient()
{
return SqlsugarHelper._Instance;
}
public T GetModel<T>(string TableName, Expression<Func<T, bool>> expressionWhere)
{
return GetModel<T>(TableName, expressionWhere, SqlsugarHelper.Instance);
}
public List<T> GetModelList<T>()
{
return GetModelList<T>(SqlsugarHelper.Instance);
}
public List<T> GetModelList<T>(string TableName)
{
return GetModelList<T>(SqlsugarHelper.Instance,TableName);
}
public List<T> Queryable<T>(Expression<Func<T, bool>> expression, string TableName)
{
return this.GetClient().Queryable<T>().AS(TableName).Where(expression).ToList();
}
public DataTable GetDataTable(string sql, List<SugarParameter> sugars = null)
{
return GetDataTable(sql, SqlsugarHelper.Instance, sugars);
}
public DataTable GetDataTable(string sql, SqlSugarClient db, List<SugarParameter> sugars = null)
{
return db.Ado.GetDataTable(sql, sugars);
}
private T GetModel<T>(object id, ISqlSugarClient db)
{
return db.Queryable<T>().InSingle(id);
}
public T GetModel<T>(string
TableName, Expression<Func<T, bool>> expressionWhere, ISqlSugarClient db)
{
return db.Queryable<T>().AS(TableName).Where(expressionWhere).First();
}
public List<T> GetModelList<T>(ISqlSugarClient db)
{
return db.Queryable<T>().ToList();
}
public List<T> GetModelList<T>(ISqlSugarClient db,string TableName)
{
return db.Queryable<T>().AS(TableName).ToList();
}
public List<T> GetModelList<T>(Expression<Func<T, bool>> expressionWhere)
{
return GetModelList<T>(expressionWhere, SqlsugarHelper.Instance);
}
public List<T> GetModelList<T>(Expression<Func<T, bool>> expressionWhere, SqlSugarClient db)
{
return db.Queryable<T>().Where(expressionWhere).ToList();
}
public List<T> GetModelList<T>(string TableName, Expression<Func<T, bool>> expressionWhere)
{
return GetModelList<T>(TableName, expressionWhere, SqlsugarHelper.Instance);
}
public List<T> GetModelList<T>(string TableName, Expression<Func<T, bool>> expressionWhere, ISqlSugarClient db)
{
return db.Queryable<T>().AS(TableName).Where(expressionWhere).ToList();
}
#region 从缓存中获取一个实体
public T GetModel_WithCache<T>(object id)
{
return GetModel_WithCache<T>(id, Instance);
}
public T GetModel_WithCache<T>(object id, SqlSugarClient db)
{
return db.Queryable<T>().WithCache().InSingle(id);
}
#endregion
#endregion
#region 添加
public int InsertModel<T>(T t, string TableName) where T : class, new()
{
return InsertModel(t, TableName, SqlsugarHelper.Instance);
}
public int InsOrUpadteModel<T>(T t,string TableName, Expression<Func<T, object>> columns, Expression<Func<T, object>> UpdateColumns = null, Expression<Func<T, object>> ignoreColumns=null) where T : class, new()
{
return InsOrUpadteModel(t, TableName, columns, SqlsugarHelper.Instance, UpdateColumns,ignoreColumns);
}
public int InsOrUpadteModel<T>(T t) where T : class, new()
{
return InsOrUpadteModel(t, SqlsugarHelper.Instance);
}
public int InsertModel<T>(T t, string TableName, ISqlSugarClient db) where T : class, new()
{
return db.Insertable(t).AS(TableName).ExecuteCommand();
}
public int InsOrUpadteModel<T>(T t,string TableName, Expression<Func<T, object>> columns, SqlSugarClient db) where T : class, new()
{
int count = 0;
var x = db.Storageable(t).As(TableName).WhereColumns(columns).ToStorage();
count+= x.AsInsertable.ExecuteCommand();
count+= x.AsUpdateable.IgnoreColumns().ExecuteCommand();
return count;
}
private int InsOrUpadteModel<T>(T t, string TableName, Expression<Func<T, object>> columns, ISqlSugarClient db, Expression<Func<T, object>> UpdateColumns=null, Expression<Func<T, object>> ignoreColumns=null) where T : class, new()
{
int count = 0;
var x = db.Storageable(t).As(TableName).WhereColumns(columns).ToStorage();
count += x.AsInsertable.ExecuteCommand();
if(UpdateColumns!=null && ignoreColumns==null)
{
count += x.AsUpdateable.UpdateColumns(UpdateColumns).ExecuteCommand();
}
else if(ignoreColumns!=null && UpdateColumns==null)
{
count += x.AsUpdateable.IgnoreColumns(ignoreColumns).ExecuteCommand();
}
else
{
count += x.AsUpdateable.ExecuteCommand();
}
return count;
}
public int InsOrUpadteModel<T>(T t, SqlSugarClient db) where T : class, new()
{
int count = 0;
var x = db.Storageable(t).ToStorage();
count += x.AsInsertable.ExecuteCommand();
count += x.AsUpdateable.ExecuteCommand();
return count;
}
public int BulkCopyModel<T>(List<T> t, string TableName, Expression<Func<T, object>> WhereColumns) where T : class, new()
{
return BulkCopyModel(t, TableName, WhereColumns, SqlsugarHelper.Instance);
}
public int _BulkCopyModel<T>(List<T> t, string TableName, Expression<Func<T, object>> WhereColumns) where T : class, new()
{
return BulkCopyModel(t, TableName, WhereColumns, SqlsugarHelper._Instance);
}
public int BulkCopyModel<T>(List<T> t, string TableName, Expression<Func<T, object>> WhereColumns, ISqlSugarClient db) where T : class, new()
{
var x = db.Storageable<T>(t).As(TableName).WhereColumns(WhereColumns).ToStorage();
int I = x.AsInsertable.ExecuteCommand();
int U = x.AsUpdateable.ExecuteCommand();
return I + U;
}
public int BulkInsertModel<T>(List<T> t, string TableName) where T : class, new()
{
return BulkInsertModel(t, TableName, SqlsugarHelper.Instance);
}
private int BulkInsertModel<T>(List<T> t, string TableName, SqlSugarClient db) where T : class, new()
{
return db.Fastest<T>().AS(TableName).BulkCopy(t);
}
public int InsertModel<T>(T t) where T : class, new()
{
return InsertModel(t, SqlsugarHelper.Instance);
}
public int InsertModels<T>(List<T> t, string TableName, Expression<Func<T, object>> ignoreColumns) where T : class, new()
{
return InsertModels(t, TableName, ignoreColumns, SqlsugarHelper.Instance);
}
public int InsertModel<T>(T t, SqlSugarClient db) where T : class, new()
{
return db.Insertable(t).
IgnoreColumns(true, false).ExecuteReturnIdentity();
}
public long InsertModel_BigIdentity<T>(T t) where T : class, new()
{
return InsertModel_BigIdentity(t, SqlsugarHelper.Instance);
}
public long InsertModel_BigIdentity<T>(T t, SqlSugarClient db) where T : class, new()
{
return db.Insertable(t).
IgnoreColumns(true, false).ExecuteReturnBigIdentity();
}
private int InsertModels<T>(List<T> t, string TableName, Expression<Func<T, object>> ignoreColumns, ISqlSugarClient db) where T : class, new()
{
return db.Insertable(t).AS(TableName).IgnoreColumns(ignoreColumns).UseParameter().ExecuteCommand();
}
#region 删除缓存
public int InsertModel_RemoveDataCache<T>(T t) where T : class, new()
{
return InsertModel_RemoveDataCache(t, SqlsugarHelper.Instance);
}
public int InsertModel_RemoveDataCache<T>(T t, SqlSugarClient db) where T : class, new()
{
return db.Insertable(t).
IgnoreColumns(true, false).RemoveDataCache().ExecuteReturnIdentity();
}
public long InsertModel_BigIdentity_RemoveDataCache<T>(T t) where T : class, new()
{
return InsertModel_BigIdentity_RemoveDataCache(t, SqlsugarHelper.Instance);
}
public long InsertModel_BigIdentity_RemoveDataCache<T>(T t, SqlSugarClient db) where T : class, new()
{
return db.Insertable(t).
IgnoreColumns(true, false).RemoveDataCache().ExecuteReturnBigIdentity();
}
#endregion
#endregion
#region 更新
public int UpdateModelByKey<T>(T t, string TableName, Expression<Func<T, object>> UpdateColumns = null, Expression<Func<T, object>> ignoreColumns = null) where T : class, new()
{
return UpdateModelByKey(t, TableName, SqlsugarHelper.Instance, ignoreColumns, UpdateColumns);
}
public int UpdateModel <T>(T t, string TableName) where T : class, new()
{
return UpdateModel(t, TableName, SqlsugarHelper.Instance);
}
public int UpdateModelByKey<T>(T t, string TableName, SqlSugarClient db, Expression<Func<T, object>> updateColumns = null, Expression<Func<T, object>> ignoreColumns = null) where T : class, new()
{
if (updateColumns != null && ignoreColumns == null)
{
return db.Updateable(t).AS(TableName).UpdateColumns(ignoreColumns).ExecuteCommand();
}
else if(ignoreColumns!=null && updateColumns==null)
{
return db.Updateable(t).AS(TableName).IgnoreColumns(ignoreColumns).ExecuteCommand();
}
else
{
return db.Updateable(t).AS(TableName).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
}
}
public int UpdateModel<T>(T t, string TableName, SqlSugarClient db) where T : class, new()
{
return db.Updateable(t).AS(TableName).ExecuteCommand();
}
public int UpdateModelsIgnoreNull<T>(T t, Expression<Func<T, bool>> expressionWhere) where T : class, new()
{
return UpdateModelsIgnoreNull(t, expressionWhere, SqlsugarHelper.Instance);
}
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();
}
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);
}
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();
}
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);
}
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).
Where(expressionWhere).ExecuteCommand();
}
public int BulkUpdata<T>(List<T> t, string TableName, string[] whereColumns = null, string[] updateColumns = null) where T : class, new()
{
return BulkUpdata(t, TableName, SqlsugarHelper.Instance, whereColumns, updateColumns);
}
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 删除缓存
public int UpdateModelByKey_RemoveDataCache<T>(T t) where T : class, new()
{
return UpdateModelByKey_RemoveDataCache(t, SqlsugarHelper.Instance);
}
public int UpdateModelByKey_RemoveDataCache<T>(T t, SqlSugarClient db) where T : class, new()
{
return db.Updateable(t).IgnoreColumns(ignoreAllNullColumns: true).RemoveDataCache().ExecuteCommand();
}
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);
}
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();
}
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);
}
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).
Where(expressionWhere).RemoveDataCache().ExecuteCommand();
}
#endregion
#endregion
#region 删除方法
public static bool DeleteByWhereSql_ids<T>(string ids, string key = "id") where T : class, new()
{
return DeleteByWhereSql_ids<T>(ids, SqlsugarHelper.Instance, key);
}
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;
}
public static bool DeleteByIds<T>(string ids) where T : class, new()
{
return DeleteByIds<T>(ids, SqlsugarHelper.Instance);
}
public static bool DeleteByIds<T>(string ids, SqlSugarClient db) where T : class, new()
{
return db.Deleteable<T>(GetIntListByString(ids)).ExecuteCommand() > 0;
}
public static bool DeleteByInt64_Ids<T>(string ids) where T : class, new()
{
return DeleteByInt64_Ids<T>(ids, SqlsugarHelper.Instance);
}
public static bool DeleteByInt64_Ids<T>(string ids, SqlSugarClient db) where T : class, new()
{
return db.Deleteable<T>(GetLongListByString(ids)).ExecuteCommand() > 0;
}
public int Deleteable<T>(string TableName, Expression<Func<T, bool>> expression) where T : class, new()
{
return Deleteable( TableName, expression, SqlsugarHelper.Instance);
}
public static int Deleteable<T>(string TableName,Expression<Func<T, bool>> expression, SqlSugarClient db) where T : class, new()
{
return db.Deleteable<T>().AS(TableName).Where(expression).ExecuteCommand();
}
#region 删除缓存
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);
}
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;
}
public static bool DeleteByIds_RemoveDataCache<T>(string ids) where T : class, new()
{
return DeleteByIds_RemoveDataCache<T>(ids, Instance);
}
public static bool DeleteByIds_RemoveDataCache<T>(string ids, SqlSugarClient db) where T : class, new()
{
return db.Deleteable<T>(GetIntListByString(ids)).RemoveDataCache().ExecuteCommand() > 0;
}
public static bool DeleteByInt64_Ids_RemoveDataCache<T>(string ids) where T : class, new()
{
return DeleteByInt64_Ids_RemoveDataCache<T>(ids, Instance);
}
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转集合
public static int[] GetIntListByString(string ids)
{
if (string.IsNullOrWhiteSpace(ids)) return null;
return Array.ConvertAll<string, int>(ids.Split(','), Int32.Parse);
}
public static long[] GetLongListByString(string ids)
{
if (string.IsNullOrWhiteSpace(ids)) return null;
return Array.ConvertAll<string, long>(ids.Split(','), Int64.Parse);
}
#endregion
#region 扩展查询,不建议使用
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);
}
}
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);
}
}
public DataTable Query(string sql, List<SugarParameter> parameters)
{
var dt = SqlsugarHelper.Instance.Ado.GetDataTable(sql, parameters);
return dt;
}
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];
}
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("]"))
)
{
whereSql.AppendFormat(" and {0} like @{1} ", keyDic.Key, keyName);
}
else if (keyDic.Value.ToString().Contains("|"))
{
whereSql.AppendFormat(" Or {0} = @{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();
}
private string getParameterName(string key)
{
var temp = key.Split('.');
StringBuilder sb = new StringBuilder(temp[temp.Length - 1]);
sb.Replace("[", string.Empty).Replace("]", string.Empty);
sb.Replace("|", string.Empty);
return sb.ToString();
}
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());
}
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}=@{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;
}
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}=@{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}=@{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;
}
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
}
#region 动态拼接lambda表达式
public static class Utility
{
public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
{
var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);
var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.AndAlso);
}
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.OrElse);
}
}
public class ParameterRebinder : ExpressionVisitor
{
private readonly Dictionary<ParameterExpression, ParameterExpression> map;
public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
{
this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
}
public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
{
return new ParameterRebinder(map).Visit(exp);
}
protected override Expression VisitParameter(ParameterExpression p)
{
ParameterExpression replacement;
if (map.TryGetValue(p, out replacement))
{
p = replacement;
}
return base.VisitParameter(p);
}
}
#endregion