using System.Collections.Generic;
using System;
using System.Diagnostics;
using SqlSugar;
using System.Linq.Expressions;
using InterfaceSimulator.Utility;
public sealed class DataBaseHelper
{
public SqlSugarClient db;
public DataBaseHelper()
{
db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["sqlConnString"].ConnectionString,
DbType = DbType.SqlServer,
IsAutoCloseConnection = true
});
db.Aop.OnLogExecuted = (sql, pra) =>
{
Console.WriteLine($"sql语句:{sql}");
if (pra.Length > 0)
{
string sqlcmd = this.GetExecMsSqlCommandText(sql, pra);
}
else
{
string sqlcmd = this.GetExecMsSqlCommandText(sql);
}
};
}
public List<T> Query<T>()
{
List<T> Result = null;
Result = db.Queryable<T>().ToList();
return Result;
}
public List<T> Query<T>(Expression<Func<T, bool>> whereExp)
{
List<T> Result = null;
Result = db.Queryable<T>().Where(whereExp).ToList();
return Result;
}
public List<T> Query<T>(Expression<Func<T, bool>> whereExp,PageModel pageModel, Expression<Func<T,object>> orderByExp=null,OrderByType orderByType= OrderByType.Asc)
{
List<T> Result = null;
Result = db.Queryable<T>().OrderBy(orderByExp,orderByType).Where(whereExp).ToPageList(pageModel.PageIndex,pageModel.PageSize); return Result;
}
public int Add<T>(T info) where T : class, new()
{
int result = -1;
result = db.Insertable(info).ExecuteCommand();
return result;
}
public int Delete<T>(dynamic id) where T : class, new()
{
int result = -1;
result = db.Deleteable<T>().In(id).ExecuteCommand();
return result;
}
public int Delete<T>(Expression<Func<T, bool>> whereExp) where T : class, new()
{
int result = -1;
result = db.Deleteable<T>().Where( whereExp ).ExecuteCommand();
return result;
}
public int Update<T>(T info) where T : class, new()
{
int result = -1;
result = db.Updateable<T>(info).ExecuteCommand();
return result;
}
/// <summary>
/// 通过sqlcommand 获取sql语句
/// </summary>
/// <param name="sqlCommand"></param>
/// <returns></returns>
private string GetExecMsSqlCommandText(string sql, SugarParameter[] param = null)
{
string sqlCmd = sql;
if (param != null)
{
foreach (var p in param)
{
string name = p.ParameterName;
object value = p.Value;
string repValue = "Null";
if (p.Value == DBNull.Value)
{ }
else
{
if ((p.DbType == System.Data.DbType.Int32) || (p.DbType == System.Data.DbType.Int64))
{
repValue = value.ToString();
}
else if (p.DbType == System.Data.DbType.String)
{
repValue = string.Format("'{0}'", value.ToString());
}
else if (p.DbType == System.Data.DbType.DateTime)
{
repValue = string.Format("'{0}'", ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss"));
}
}
sqlCmd = sqlCmd.Replace(name, repValue);
}
}
Logger.Debug("exec sql:" + sql);
return sqlCmd;
}
}