using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using System.Collections.Generic;
using LYFZ.Helper;
using System.Reflection;
using System.Collections.Concurrent;
using System.Linq.Expressions;
using System.Collections;
using System.Linq;
using LYFZ.WinAPI;
using System.Dynamic;
using Newtonsoft.Json;
namespace LYFZ.WanYuKeFuData.DAL
{
///
/// 数据操作抽象基类
///
public abstract class BaseDataOperate
{
#region 属性
LYFZ.WanYuKeFuData.Model.DBConnection _DBConn;
///
/// 当前数据库连接对象
///
protected LYFZ.WanYuKeFuData.Model.DBConnection DBConn
{
get
{
return this._DBConn;
}
set
{
this._DBConn = value;
}
}
///
/// 获取当前新的数据表模型对象
///
public T ObjModel
{
get
{
return Activator.CreateInstance();
}
}
///
/// 数据表名
///
public string TableName
{
get{
return "tb_"+typeof(T).Name;
}
// set;
}
string _TableFieldNameStr = "";
///
/// 数据表字段名字符串,字段名以“,”号分隔
///
public string TableFieldNameStr
{
get
{
if (this._TableFieldNameStr.Trim() == "")
{
foreach (string fieldName in this.TableFieldNames)
{
if (this._TableFieldNameStr.Trim() == "")
{
this._TableFieldNameStr += "[" + fieldName + "]";
}
else
{
this._TableFieldNameStr += ",[" + fieldName + "]";
}
}
}
if (this._TableFieldNameStr.Trim() == "")
{
this._TableFieldNameStr = "*";
}
return this._TableFieldNameStr;
}
set { this._TableFieldNameStr = value; }
}
///
/// 数据表字段名数组
///
public string[] TableFieldNames
{
get
{
System.Reflection.PropertyInfo[] propertyInfos = this.PropertyInfos;
List fieldNameList = new List();
foreach (System.Reflection.PropertyInfo propertyInfo in propertyInfos)
{
if (!propertyInfo.IsSpecialName)
{
fieldNameList.Add(propertyInfo.Name);
}
}
return fieldNameList.ToArray();
}
}
///
/// 获取要查询的当前表的字段集合字符串 用","号分隔
///
///
/// 如果为true 表示只返回 filters 集合中的字段 如果为false 表示返回排除 filters 集合中的字段以外的所有字段
///
public string GetQueryTableFieldNames(string[] filters = null, bool isContain = false)
{
List tempFilters = new List();
if (filters != null)
{
tempFilters.AddRange(filters);
}
System.Reflection.PropertyInfo[] propertyInfos = this.PropertyInfos;
string fieldNames = "";
for (int i = 0; i < propertyInfos.Length; i++)
{
if (!propertyInfos[i].IsSpecialName)
{
System.Reflection.PropertyInfo propertyInfo = propertyInfos[i];
if ((!tempFilters.Contains(propertyInfo.Name) && !isContain) || (tempFilters.Contains(propertyInfo.Name) && isContain))
{
if (fieldNames.Trim().Length <= 0)
{
fieldNames = "[" + propertyInfo.Name + "]";
}
else
{
fieldNames += ",[" + propertyInfo.Name + "]";
}
}
}
}
return fieldNames;
}
///
/// 获取属性集合
///
public System.Reflection.PropertyInfo[] PropertyInfos
{
get
{
List list = new List();
System.Reflection.PropertyInfo[] infos = ObjModel.GetType().GetProperties();
foreach (System.Reflection.PropertyInfo info in infos)
{
if (info.CanWrite)
{
list.Add(info);
}
}
return list.ToArray();
}
}
#endregion
#region 检查记录
///
/// 是否存在该记录
///
public bool Exists(int id)
{
return this.Exists("ID", id);
}
///
/// 根据筛选条件判断是否存在该记录
///
/// 筛选字段名
/// 筛选值
///
public bool Exists(string filterFieldName, object filterValue)
{
if (filterFieldName != "" && filterValue != null)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select count(1) from " + this.TableName + " ");
strSql.Append(" where 1=1 and " + filterFieldName + "=@" + filterFieldName);
SqlParameter[] parameters = {
new SqlParameter("@"+filterFieldName, filterValue)
};
return SQLHelper.Exists(strSql.ToString(), this.DBConn.DBConnectionString, parameters);
}
else
{
return false;
}
}
///
/// 根据筛选条件判断是否存在该记录
///
/// 筛选字段名
/// 筛选值
///
public bool Exists(string whereString)
{
if (whereString.Trim().Length > 0)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select count(1) from " + this.TableName + " ");
strSql.Append(" where " + whereString);
return SQLHelper.Exists(strSql.ToString(), this.DBConn.DBConnectionString);
}
else
{
return false;
}
}
///
/// 判断是否存某个字段
///
/// 列名称
/// 是否存在
public bool ColumnExists(string columnName)
{
return SQLHelper.ColumnExists(this.TableName, columnName, this.DBConn.DBConnectionString);
}
#endregion
#region 公共方法
///
/// 获取最大ID()
///
///
public int GetMaxID()
{
return this.GetMaxID("ID");
}
///
/// 获取某字段最大值(获取字段必须为数字类型)
///
/// 字段名
///
public int GetMaxID(string FieldName)
{
return SQLHelper.GetMaxID(FieldName, this.TableName, this.DBConn.DBConnectionString);
}
#endregion
#region 判断方法
///
/// 获取是否为忽略字段 返回 true 表示忽略 false 不忽略
///
/// 忽略字段名列表 字段名之间用“,”号分隔
/// 要判断的字段名
///
public bool IsOverlookFiel(string overlookFieldList, string fieldName)
{
bool bl = false;
string[] tempOverlookFieldList = overlookFieldList.Split(',');
for (int i = 0; i < tempOverlookFieldList.Length; i++)
{
if (tempOverlookFieldList[i].Trim().ToLower() == fieldName.Trim().ToLower())
{
bl = true;
break;
}
}
return bl;
}
#endregion
#region 增加数据
///
/// 增加一条数据
///
/// Model对象
/// 忽略字段名列表 字段名之间用“,”号分隔
///
public bool Add(T model, string overlookFieldList = "ID")
{
LYFZ.Helper.CommandInfo comdInfo = this.GetAddCommandInfo(model, overlookFieldList);
int rows = SQLHelper.ExecuteSql(comdInfo.CommandText, this.DBConn.DBConnectionString, (SqlParameter[])comdInfo.Parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
///
/// 获取插入数CommandInfo对象
///
///
/// 要忽略的字段集合 多个字段名有“,”号分隔
///
public object GetAddCommandInfoObject(T model, string overlookFieldList = "ID")
{
return this.GetAddCommandInfo(model, overlookFieldList);
}
///
/// 获取插入数CommandInfo对象
///
///
/// 要忽略的字段集合 多个字段名有“,”号分隔
///
///
public LYFZ.Helper.CommandInfo GetAddCommandInfo(T model, string overlookFieldList = "ID", EffentNextType type = EffentNextType.None)
{
StringBuilder strSql = new StringBuilder();
StringBuilder tempFieldNameString = new StringBuilder();
StringBuilder tempValueVariable = new StringBuilder();
List parameterlist = new List();
for (int i = 0; i < PropertyInfos.Length; i++)
{
try
{
System.Reflection.PropertyInfo propertyInfo = PropertyInfos[i];
string tempFieldName = propertyInfo.Name;
object tempValue = propertyInfo.GetValue(model, null);
Type tempType = propertyInfo.PropertyType;
if (!IsOverlookFiel(overlookFieldList, tempFieldName) || (tempFieldName.ToLower() == "id" && tempType == typeof(long)))
{
try
{
if (tempType.Name == "DateTime")
{
if (tempValue.ToString().Contains("0001"))
{
tempValue = null;
}
try
{
DateTime tempTime;
if (!DateTime.TryParse(tempValue.ToString(), out tempTime))
{
tempValue = null;
}
else if (tempTime <= LYFZ.WinAPI.CustomPublicMethod.GetNullDateTime())
{
tempValue = null;
}
}
catch
{
tempValue = null;
}
}
else if (tempFieldName.ToLower() == "id" && tempType == typeof(long) && (tempValue == null || Convert.ToInt64(tempValue) == 0))
{
tempValue = LYFZ.WinAPI.CustomPublicMethod.GenerateId();
}
if (tempValue != null)
{
tempFieldNameString.Append("" + tempFieldName + ",");
tempValueVariable.Append("@" + tempFieldName + ",");
SqlParameter parameter = new SqlParameter("@" + tempFieldName, tempValue);
parameterlist.Add(parameter);
}
}
catch { }
}
}
catch { }
}
//去除结尾多余的“,”
if (tempFieldNameString.ToString().LastIndexOf(',') == tempFieldNameString.Length - 1)
{
tempFieldNameString.Remove(tempFieldNameString.Length - 1, 1);
}
//去除结尾多余的“,”
if (tempValueVariable.ToString().LastIndexOf(',') == tempValueVariable.Length - 1)
{
tempValueVariable.Remove(tempValueVariable.Length - 1, 1);
}
strSql.Append("insert into " + this.TableName + "(");
strSql.Append("" + tempFieldNameString.ToString() + ")");
strSql.Append(" values (");
strSql.Append("" + tempValueVariable.ToString() + ")");
strSql.Append(";select @@IDENTITY");
SqlParameter[] parameters = parameterlist.ToArray();
return new CommandInfo(strSql.ToString(), parameters, type);
}
#endregion
#region 更新数据
///
/// 根据筛选字段和SQL筛选运算符号更新数据(内部方法)
///
/// Model对象
/// 筛选字段名称
/// SQL筛选运算符号
/// 忽略字段名列表 字段名之间用“,”号分隔
/// Wher条件,当指定条件语句时筛选字段设置无效,不包含“where”关键字 不建义使用此参数
///
protected bool InsideUpdate(T model, string filterFieldName = "ID", string operators = "=", string overlookFieldList = "ID", string whereStr = null)
{
LYFZ.Helper.CommandInfo comdInfo = GetUpdateCommandInfo(model, filterFieldName, operators, overlookFieldList, whereStr);
int rows = SQLHelper.ExecuteSql(comdInfo.CommandText, this.DBConn.DBConnectionString, (SqlParameter[])comdInfo.Parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/////
///// 获取更新数据的UpdateCommandInfo对象 根据筛选字段和SQL筛选运算符号更新数据(内部方法)
/////
///// Model对象
///// 筛选字段名称
///// SQL筛选运算符号
///// 忽略字段名列表 字段名之间用“,”号分隔
///// Wher条件,当指定条件语句时筛选字段设置无效,不包含“where”关键字 不建义使用此参数
//public LYFZ.Helper.CommandInfo GetUpdateCommandInfoObject(T model, string filterFieldName = "ID", string operators = "=", string overlookFieldList = "ID", string whereStr = null)
//{
// return this.GetUpdateCommandInfo(model, filterFieldName, operators, overlookFieldList, whereStr);
//}
///
/// 获取更新数据的UpdateCommandInfo对象 根据筛选字段和SQL筛选运算符号更新数据(内部方法)
///
/// Model对象
/// 筛选字段名称
/// SQL筛选运算符号
/// 忽略字段名列表 字段名之间用“,”号分隔
/// Wher条件,当指定条件语句时筛选字段设置无效,不包含“where”关键字 不建义使用此参数
///
public LYFZ.Helper.CommandInfo GetUpdateCommandInfo(T model, string filterFieldName = "ID", string operators = "=", string overlookFieldList = "ID", string whereStr = null, EffentNextType type = EffentNextType.None)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update " + this.TableName + " set ");
List parameterlist = new List();
overlookFieldList += "," + filterFieldName;
for (int i = 0; i < PropertyInfos.Length; i++)
{
try
{
System.Reflection.PropertyInfo propertyInfo = PropertyInfos[i];
string tempFieldName = propertyInfo.Name;//字段名
object tempValue = propertyInfo.GetValue(model, null);//对应字段值
//如果字段名不为忽略字段则进行处理
if (!IsOverlookFiel(overlookFieldList, tempFieldName))
{
try
{
if (tempValue.GetType() == typeof(DateTime))
{
DateTime tempTime;
try
{
if (!DateTime.TryParse(tempValue.ToString(), out tempTime))
{
tempValue = null;
}
else if (tempTime <= LYFZ.WinAPI.CustomPublicMethod.GetNullDateTime())
{
tempValue = null;
}
else if (tempTime.Year == Convert.ToDateTime("0001-01-01").Year || tempTime.Year == Convert.ToDateTime("1753-01-01").Year)
{
tempValue = null;
}
}
catch { tempValue = null; }
}
}
catch { }
strSql.Append("" + tempFieldName + "=@" + tempFieldName + ",");
SqlParameter parameter = new SqlParameter("@" + tempFieldName, tempValue);
parameterlist.Add(parameter);
}
}
catch { }
}
//去除结尾多余的“,”
if (strSql.ToString().LastIndexOf(',') == strSql.Length - 1)
{
strSql.Remove(strSql.Length - 1, 1);
}
if (whereStr == null)
{
if (filterFieldName != "" && operators != "")
{
try
{
object FilterFieldValue = LYFZ.WinAPI.CustomPublicMethod.GetPropertyValue(model, filterFieldName);// model.GetType().GetProperty(filterFieldName).GetValue(model, null);
strSql.Append(" where " + filterFieldName + operators + "@" + filterFieldName);
parameterlist.Add(new SqlParameter("@" + filterFieldName, FilterFieldValue));
}
catch
{
}
}
}
else
{
strSql.Append(" where 1=1 and (" + whereStr + ")");
}
SqlParameter[] parameters = parameterlist.ToArray();
return new CommandInfo(strSql.ToString(), parameters, type);
}
///
/// 根据筛选字段和SQL筛选运算符号更新数据
///
/// Model对象
/// 筛选字段名称
/// SQL筛选运算符号
/// 忽略字段名列表 字段名之间用“,”号分隔
///
public bool Update(T model, string filterFieldName = "ID", string operators = "=", string overlookFieldList = "ID")
{
return InsideUpdate(model, filterFieldName, operators, overlookFieldList);
}
///
/// 根据Wher条件更新数据 不建义使用此方法
///
/// Model对象
/// Wher条件,不包含“where”关键字
/// 忽略字段名列表 字段名之间用“,”号分隔
///
public bool Update(T model, string whereStr, string overlookFieldList = "ID")
{
return InsideUpdate(model, overlookFieldList: overlookFieldList, whereStr: whereStr);
}
#endregion
#region 删除数据
///
/// 根据筛选字段或where条件删除数据
///
/// 筛选字段名
/// 筛选SQL运算符
/// 筛选值
/// Wher条件,不包含“where”关键字
///
protected bool InsideDelete(string filterFieldName = "ID", string operators = "=", object filterValue = null, string whereStr = null)
{
LYFZ.Helper.CommandInfo comdInfo = GetDeleteCommandInfo(filterFieldName, operators, filterValue, whereStr);
int rows = SQLHelper.ExecuteSql(comdInfo.CommandText, this.DBConn.DBConnectionString, (SqlParameter[])comdInfo.Parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/////
///// 根据筛选字段或where条件删除数据
/////
///// 筛选字段名
///// 筛选SQL运算符
///// 筛选值
///// Wher条件,传入条件语句时筛选字段无效不建义使用 不包含“where”关键字
/////
//public object GetDeleteCommandInfoObject(string filterFieldName = "ID", string operators = "=", object filterValue = null, string whereStr = null)
//{
// return this.GetDeleteCommandInfo(filterFieldName, operators, filterValue, whereStr);
//}
///
/// 根据筛选字段或where条件删除数据
///
/// 筛选字段名
/// 筛选SQL运算符
/// 筛选值
/// Wher条件,传入条件语句时筛选字段无效不建义使用 不包含“where”关键字
///
///
public LYFZ.Helper.CommandInfo GetDeleteCommandInfo(string filterFieldName = "ID", string operators = "=", object filterValue = null, string whereStr = null, EffentNextType type = EffentNextType.None)
{
if (filterValue == null) { filterValue = ""; }
List parameterlist = new List();
StringBuilder strSql = new StringBuilder();
strSql.Append("delete from " + this.TableName + " ");
if (whereStr == null)
{
strSql.Append(" where " + filterFieldName + "" + operators + "@" + filterFieldName + "");
parameterlist.Add(new SqlParameter("@" + filterFieldName, filterValue));
}
else
{
strSql.Append(" where ID>@ID and (" + whereStr + ")");
parameterlist.Add(new SqlParameter("@ID", Convert.ToInt32(0)));
}
SqlParameter[] parameters = parameterlist.ToArray();
return new CommandInfo(strSql.ToString(), parameters, type);
}
///
/// 删除一条数据
///
/// id
public bool Delete(long ID)
{
return this.InsideDelete(filterValue: ID);
}
///
/// 删除一条数据
///
/// id
public bool Delete(int ID)
{
return this.InsideDelete(filterValue: ID);
}
///
/// 根据筛选字段删除数据
///
/// 筛选值
/// 筛选字段名
/// 筛选SQL运算符
///
public bool Delete(object filterValue, string filterFieldName = "ID", string operators = "=")
{
return this.InsideDelete(filterFieldName, operators, filterValue);
}
///
/// 根据where条件删除数据 不建义使用此方法
///
/// Wher条件,不包含“where”关键字
///
public bool Delete(string whereStr)
{
return this.InsideDelete(whereStr: whereStr);
}
///
/// 批量删除数据
///
/// 筛选字段名
/// 值列表,多个值用“,”分隔,字符串值用“'”号包含
public bool DeleteList(string filterFieldName, string valueList)
{
if (filterFieldName != "" && valueList != "")
{
StringBuilder strSql = new StringBuilder();
strSql.Append("delete from " + this.TableName + " ");
strSql.Append(" where " + filterFieldName + " in (" + valueList + ") ");
int rows = SQLHelper.ExecuteSql(strSql.ToString(), this.DBConn.DBConnectionString);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
///
/// 按ID列表批量删除数据
///
/// ID列表,多个用“,”分隔
public bool DeleteList(string idList)
{
return this.DeleteList("ID", idList);
}
#endregion
#region 查询数据
public T DataRowToModel(DataRow dr)
{
if (dr == null)
{
return Activator.CreateInstance();
}
Dictionary dataInfo = new Dictionary();
dynamic objmatch = new ExpandoObject();
for (int i = 0; i < dr.Table.Columns.Count; i++)
{
string value = dr[dr.Table.Columns[i].ColumnName].ToString();
if (!string.IsNullOrEmpty(value))
{
dataInfo.Add(dr.Table.Columns[i].ColumnName, value);
}
}
objmatch = dataInfo;
string json = JsonConvert.SerializeObject((object)objmatch);
return DataRowToModelByEntity(json);
}
public T GetModelObjectByEntity(string filterFieldName, object filterValue)
{
DataRow dr = GetDataRow(filterFieldName, filterValue);
Dictionary dataInfo = new Dictionary();
if(dr==null)
{
return Activator.CreateInstance();
}
dynamic objmatch = new ExpandoObject();
for (int i = 0; i < dr.Table.Columns.Count; i++)
{
string value = dr[dr.Table.Columns[i].ColumnName].ToString();
if (!string.IsNullOrEmpty(value))
{
dataInfo.Add(dr.Table.Columns[i].ColumnName, value);
}
}
objmatch = dataInfo;
string json = JsonConvert.SerializeObject((object)objmatch);
return DataRowToModelByEntity(json);
}
public T DataRowToModelByEntity(int ID)
{
DataRow dr = GetDataRow(ID);
if (dr == null)
{
return Activator.CreateInstance();
}
Dictionary dataInfo = new Dictionary();
dynamic objmatch = new ExpandoObject();
for (int i = 0; i < dr.Table.Columns.Count; i++)
{
string value = dr[dr.Table.Columns[i].ColumnName].ToString();
if (!string.IsNullOrEmpty(value))
{
dataInfo.Add(dr.Table.Columns[i].ColumnName, value);
}
}
objmatch = dataInfo;
string json = JsonConvert.SerializeObject((object)objmatch);
return DataRowToModelByEntity(json);
}
T DataRowToModelByEntity(string json)
{
T obj = (T)JsonConvert.DeserializeObject(json, this.ObjModel.GetType());
return obj;
}
///
/// 得到一个Object对象实体
///
///
///
public T GetModel(long ID)
{
return DataRowToModel(GetDataRow(ID));
}
///
/// 得到一个Object对象实体
///
///
///
public T GetModel(int ID)
{
return DataRowToModel(GetDataRow(ID));
}
///
/// 根据筛选条件获取一条数据Model对象
///
/// 筛选条件字段名
/// 值
///
public T GetModel(string filterFieldName, object filterValue)
{
return DataRowToModel(GetDataRow(filterFieldName, filterValue));
}
///
/// 根据筛选条件获取一条数据Model对象
///
/// 筛选条件字段名
/// 值
/// SQL筛选运算符号
///
public T GetModel(string filterFieldName, object filterValue, string operators)
{
return DataRowToModel(GetDataRow(filterFieldName, filterValue, operators));
}
///
/// 根据筛选条件获取一条数据Model对象
///
/// 筛选条件
///
public T GetModel(string whereString)
{
return DataRowToModel(GetDataRow(whereString));
}
///
/// 获取一条数据DataRow对象
///
/// id
///
public DataRow GetDataRow(long id)
{
return GetDataRow("ID", id);
}
///
/// 获取一条数据DataRow对象
///
/// id
///
public DataRow GetDataRow(int id)
{
return GetDataRow("ID", id);
}
///
/// 根据筛选条件获取一条数据DataRow对象
///
/// 筛选条件
///
public DataRow GetDataRow(string whereString)
{
if (whereString.Trim().Length > 0)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select top 1 " + this.TableFieldNameStr + " from " + this.TableName + " ");
strSql.Append(" where " + whereString);
DataSet ds = SQLHelper.Query(strSql.ToString(), this.DBConn.DBConnectionString);
if (ds.Tables[0].Rows.Count > 0)
{
return ds.Tables[0].Rows[0];
}
else
{
return null;
}
}
else
{
return null;
}
}
///
/// 根据筛选条件获取一条数据DataRow对象
///
/// 筛选条件字段名
/// 值
/// SQL筛选运算符号
///
public DataRow GetDataRow(string filterFieldName, object filterValue, string operators = "=")
{
if (filterFieldName != "" && filterValue != null)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select top 1 " + this.TableFieldNameStr + " from " + this.TableName + " ");
strSql.Append(" where 1=1 and " + filterFieldName + "" + operators + "@" + filterFieldName + " ");
SqlParameter[] parameters = {
new SqlParameter("@"+filterFieldName, filterValue)
};
DataSet ds = SQLHelper.Query(strSql.ToString(), this.DBConn.DBConnectionString, parameters);
if (ds.Tables[0].Rows.Count > 0)
{
return ds.Tables[0].Rows[0];
}
else
{
return null;
}
}
else
{
return null;
}
}
///
/// 根据筛选条件获取一条数据DataRow对象(运算符是“=”)
///
/// 筛选条件字段名
/// 值
///
public DataRow GetDataRow(string filterFieldName, object filterValue)
{
return GetDataRow(filterFieldName, filterValue, "=");
}
///
/// 得到一个对象实体
///
public T DataRowToModel(DataRow row, T model)
{
if (row != null)
{
for (int i = 0; i < PropertyInfos.Length; i++)
{
try
{
System.Reflection.PropertyInfo propertyInfo = PropertyInfos[i];
string tempFieldName = propertyInfo.Name;//字段名
if (row[tempFieldName] != null)
{
object tempValue = row[tempFieldName];//对应字段值
LYFZ.WinAPI.CustomPublicMethod.SetPropertyValue(model, propertyInfo, tempValue);
}
}
catch
{
}
}
}
return model;
}
///
/// 获得数据列表
///
/// 条件语句 不包含 where 关键字
/// SQL排序 如:id desc
public DataSet GetList(string strWhere, string filedOrder = "ID asc")
{
return this.GetList(0, strWhere, filedOrder);
}
///
/// 获得全部数据列表
///
/// SQL排序 如:id desc
public DataSet GetAllList(string filedOrder = "ID asc")
{
return this.GetList("", filedOrder);
}
///
/// 获得全部数据列表
///
/// SQL排序 如:id desc
public List GetAllModelList(string filedOrder = "ID asc")
{
DataTable tb = this.GetAllList(filedOrder).Tables[0];
List modelList = new List();
foreach (DataRow row in tb.Rows)
{
modelList.Add(this.DataRowToModel(row));
}
return modelList;
}
///
/// 获得前几行数据
///
/// 行数
/// 条件 不包含 where 关键字
/// SQL排序 如:id asc
///
public DataSet GetList(int Top, string strWhere, string filedOrder = "ID asc")
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select ");
if (Top > 0)
{
strSql.Append(" top " + Top.ToString());
}
strSql.Append(" " + this.TableFieldNameStr + " from " + this.TableName + " ");
if (strWhere.Trim() != "")
{
strSql.Append(" where 1=1 and (" + strWhere + ")");
}
strSql.Append(" order by " + filedOrder);
DataSet ds = SQLHelper.Query(strSql.ToString(), this.DBConn.DBConnectionString);
ds.Tables[0].TableName = this.TableName;
return ds;
}
#endregion
#region 数据分页
///
/// 获取记录总数
///
public int GetRecordCount(string strWhere)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select count(1) FROM " + this.TableName + " ");
if (strWhere.Trim() != "")
{
strSql.Append(" where 1=1 and (" + strWhere + ")");
}
object obj = SQLHelper.GetSingle(strSql.ToString(), this.DBConn.DBConnectionString);
if (obj == null)
{
return 0;
}
else
{
return Convert.ToInt32(obj);
}
}
///
/// 获取分页后总页数
///
/// 筛选条件
/// 页面大小
///
public int GetByPageCount(string strWhere, int pageSize)
{
int pageCount = 0;
if (pageSize > 0)
{
int allCount = GetRecordCount(strWhere);
pageCount = allCount / pageSize;
if (pageCount * pageSize < allCount)
{
pageCount++;
}
}
return pageCount;
}
///
/// 分页获取数据列表
///
/// 筛选条件
/// 当前页 不能小于0的整数
/// 页面大小,每页显示条数 不能小于0的整数
/// 排序
///
public DataSet GetListByPage(string strWhere, int pageIndex, int pageSize, string orderby = "id desc")
{
return this.GetListByPage(strWhere, orderby, (pageIndex - 1) * pageSize, pageIndex * pageSize);
}
///
/// 分页获取数据列表
///
/// 筛选条件
/// 排序
/// 当前页
/// 页面大小,每页显示条数
/// 返回总页数
///
public DataSet GetListByPage(string strWhere, string orderby, int pageIndex, int pageSize, ref int pageCount)
{
pageCount = GetByPageCount(strWhere, pageSize);
return this.GetListByPage(strWhere, orderby, (pageIndex - 1) * pageSize, pageIndex * pageSize);
}
///
/// 分页获取数据列表
///
/// 条件
/// 排序
/// 开始index
/// 结束index
///
public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
{
if (!string.IsNullOrEmpty(strWhere.Trim()))
{
strWhere = " Where " + strWhere;
}
if (!string.IsNullOrEmpty(orderby.Trim()))
{
orderby = " Order By " + orderby;
}
StringBuilder strSql = new StringBuilder();
strSql.Append("SELECT * FROM " + this.TableName + " Where ID Not IN ");
strSql.Append("(Select Top " + startIndex + " ID From " + this.TableName + " " + strWhere + orderby + ")");
strSql.Append(" And ID In ");
strSql.Append("(Select Top " + endIndex + " ID From " + this.TableName + " " + strWhere + orderby + ")");
strSql.Append(orderby);
DataSet ds = SQLHelper.Query(strSql.ToString(), this.DBConn.DBConnectionString);
ds.Tables[0].TableName = this.TableName;
return ds;
}
#endregion
#region 杨云奕添加 17-04-09 优化sql新增修改的方法
///
/// 通过泛型实体生成更新语句和对象
///
///
///
///
///
///
///
///
///
public LYFZ.Helper.CommandInfo GetUpdateCommandInfoByEntity(T date, string filterFieldName = "ID",
string operators = "=", string overlookFieldList = "ID", string whereStr = null,
EffentNextType type = EffentNextType.None)
{
var properties = ReflectionHelper.GetProperties(typeof(T));
StringBuilder strSql = new StringBuilder();
Dictionary dicWhereData = new Dictionary();
strSql.Append("update " + this.TableName + " set ");
List parameterlist = new List();
var ignorePropertyNames = new HashSet();
var filterPropertyNames = new HashSet();
///跳过的字段数据
if (!string.IsNullOrEmpty(overlookFieldList))
{
foreach (var msg in overlookFieldList.Split(','))
{
ignorePropertyNames.Add(msg);
}
}
///用于查询的where条件的数据
if (!string.IsNullOrEmpty(filterFieldName))
{
foreach (var msg in filterFieldName.Split(','))
{
filterPropertyNames.Add(msg);
}
}
foreach (var property in properties)
{
var ignoreProperty = ignorePropertyNames.SingleOrDefault(x => x.Equals(property.Value.Name, StringComparison.CurrentCultureIgnoreCase));
var filterProperty = filterPropertyNames.SingleOrDefault(x => x.Equals(property.Value.Name, StringComparison.CurrentCultureIgnoreCase));
if (filterProperty != null)
{
dicWhereData.Add(property.Key, property.Value);
}
if (ignoreProperty != null)
continue;
var propertyType = ReflectionHelper.GetPropertyType(property.Value);
if( propertyType.Name.ToLower().IndexOf("list")!=-1)
{
continue;
}
var propertyValue = ReflectionHelper.GetPropertyValue(date, property.Value);
if (propertyValue == null)
{
continue;
}
else if (propertyValue != null && propertyType.Name.ToLower().Equals("datetime") && propertyValue.ToString().Contains("0001"))
{
continue;
}
else if (propertyValue != null && propertyType.Name.ToLower().Equals("datetime") && Convert.ToDateTime(propertyValue) <= LYFZ.WinAPI.CustomPublicMethod.GetNullDateTime())
{
continue;
}
// ColumnAction(property.Value.Name, propertyValue, propertyType, DataTypes.Object, 0);
if (propertyValue != null)
{
strSql.Append("" + property.Key + "=@" + property.Key + ",");
SqlParameter parameter = new SqlParameter("@" + property.Key, propertyValue);
parameterlist.Add(parameter);
}
}
//去除结尾多余的“,”
if (strSql.ToString().LastIndexOf(',') == strSql.Length - 1)
{
strSql.Remove(strSql.Length - 1, 1);
}
if (whereStr == null)
{
if (filterFieldName != "" && operators != "")
{
string strWhere = "";
foreach (var property in dicWhereData)
{
if (!string.IsNullOrEmpty(strWhere))
{
strWhere += " and ";
}
strWhere += property.Key + operators + "@" + property.Key;
var propertyValue = ReflectionHelper.GetPropertyValue(date, property.Value);
parameterlist.Add(new SqlParameter("@" + property.Key, propertyValue));
}
strSql.Append(" where " + strWhere);
}
}
else
{
strSql.Append(" where 1=1 and (" + whereStr + ")");
}
SqlParameter[] parameters = parameterlist.ToArray();
return new CommandInfo(strSql.ToString(), parameters, type);
}
///
/// 通过泛型方法生成新增对象信息
///
///
///
///
///
///
public LYFZ.Helper.CommandInfo GetAddCommandInfoByEntity(T date,
string overlookFieldList = "ID",
EffentNextType type = EffentNextType.None)
{
StringBuilder strSql = new StringBuilder();
var properties = ReflectionHelper.GetProperties(typeof(T));
StringBuilder tempFieldNameString = new StringBuilder();
StringBuilder tempValueVariable = new StringBuilder();
List parameterlist = new List();
var ignorePropertyNames = new HashSet();
if (!string.IsNullOrEmpty(overlookFieldList))
{
foreach (var msg in overlookFieldList.Split(','))
{
ignorePropertyNames.Add(msg);
}
}
foreach (var property in properties)
{
var ignoreProperty = ignorePropertyNames.SingleOrDefault(x => x.Equals(property.Value.Name, StringComparison.CurrentCultureIgnoreCase));
if (ignoreProperty != null)
continue;
var propertyType = ReflectionHelper.GetPropertyType(property.Value);
if (propertyType.Name.ToLower().IndexOf("list") != -1)
{
continue;
}
var propertyValue = ReflectionHelper.GetPropertyValue(date, property.Value);
if (propertyValue==null)
{
continue;
}
if (propertyValue != null && propertyType.Name.ToLower().Equals("datetime") && propertyValue.ToString().Contains("0001"))
{
continue;
}
if (propertyValue != null && propertyType.Name.ToLower().Equals("datetime") && Convert.ToDateTime(propertyValue) <= LYFZ.WinAPI.CustomPublicMethod.GetNullDateTime())
{
continue;
}
else if (property.Key.ToLower() == "id" && propertyType == typeof(long) && (propertyValue == null || Convert.ToInt64(propertyValue) == 0))
{
propertyValue = LYFZ.WinAPI.CustomPublicMethod.GenerateId();
}
if (propertyValue != null)
{
tempFieldNameString.Append("" + property.Key + ",");
tempValueVariable.Append("@" + property.Key + ",");
SqlParameter parameter = new SqlParameter("@" + property.Key, propertyValue);
parameterlist.Add(parameter);
}
}
if (tempFieldNameString.ToString().LastIndexOf(',') == tempFieldNameString.Length - 1)
{
tempFieldNameString.Remove(tempFieldNameString.Length - 1, 1);
}
//去除结尾多余的“,”
if (tempValueVariable.ToString().LastIndexOf(',') == tempValueVariable.Length - 1)
{
tempValueVariable.Remove(tempValueVariable.Length - 1, 1);
}
strSql.Append("insert into " + this.TableName + "(");
strSql.Append("" + tempFieldNameString.ToString() + ")");
strSql.Append(" values (");
strSql.Append("" + tempValueVariable.ToString() + ")");
strSql.Append(";select @@IDENTITY");
SqlParameter[] parameters = parameterlist.ToArray();
return new CommandInfo(strSql.ToString(), parameters, type);
}
public object GetAddCommandInfoByEntity(T date, string overlookFieldList = "ID")
{
return GetAddCommandInfoByEntity(date, overlookFieldList, EffentNextType.None);
}
public object GetUpdateCommandInfoByEntity(T date, string filterFieldName = "ID", string operators = "=", string overlookFieldList = "ID", string whereStr = null)
{
return GetUpdateCommandInfoByEntity(date, filterFieldName, operators, overlookFieldList, whereStr, EffentNextType.None);
}
#endregion
///
/// 转Json数据为Model
///
///
///
///
public static T JsonToModelByEntity(string json)
{
T t = Activator.CreateInstance();
T obj = (T)Newtonsoft.Json.JsonConvert.DeserializeObject(json, t.GetType());
return obj;
}
///
/// 分页查询记录
///
///
public DataSet PagingQueryDataTable(string _pageTableName, string _QueryFieldName, string _OrderStr, string _QueryCondition, int _PageSize, int _PageIndex, out int _TotalCount)
{
SqlParameter[] parameters = {
new SqlParameter("@TableName", SqlDbType.VarChar , 2000),
new SqlParameter("@ReFieldsStr" , SqlDbType.VarChar , 2000),
new SqlParameter("@OrderString", SqlDbType.VarChar , 2000 ),
new SqlParameter("@WhereString", SqlDbType.VarChar, 2000),
new SqlParameter("@PageSize", SqlDbType.Int),
new SqlParameter("@PageIndex", SqlDbType.Int),
new SqlParameter("@TotalRecord", SqlDbType.Int)
};
parameters[0].Value = _pageTableName;
parameters[1].Value = _QueryFieldName;
parameters[2].Value = _OrderStr;
parameters[3].Value = _QueryCondition;
parameters[4].Value = _PageSize;
parameters[5].Value = _PageIndex;
parameters[6].Direction = ParameterDirection.Output;
DataSet ds = LYFZ.Helper.SQLHelper.RunProcedure("PROCE_SQL2005PAGECHANGE", parameters, _pageTableName + "_ds",this._DBConn.GetDBConnectionString());
_TotalCount = Convert.ToInt32(parameters[6].Value);
//if (_TotalCount == 0)
//{
// _PageCount = 0;
//}
//else
//{
// _PageCount = _TotalCount % _PageSize == 0 ? _TotalCount / _PageSize : _TotalCount / _PageSize + 1;
//}
return ds;
}
}
#region 杨云奕添加 17-04-09 反射助手,用于泛型实体的反射操作
internal static class ReflectionHelper
{
private static readonly ConcurrentDictionary> _cachedProperties = new ConcurrentDictionary>();
///
/// 得到实体反射的表达式
///
///
///
///
public static string GetPropertyNameFromExpression(Expression> expression)
{
string propertyPath = null;
if (expression.Body is UnaryExpression)
{
var unaryExpression = (UnaryExpression)expression.Body;
if (unaryExpression.NodeType == ExpressionType.Convert)
propertyPath = unaryExpression.Operand.ToString();
}
if (propertyPath == null)
propertyPath = expression.Body.ToString();
propertyPath = propertyPath.Replace(expression.Parameters[0] + ".", string.Empty);
return propertyPath;
}
public static List GetPropertyNamesFromExpressions(Expression>[] expressions)
{
var propertyNames = new List();
foreach (var expression in expressions)
{
var propertyName = GetPropertyNameFromExpression(expression);
propertyNames.Add(propertyName);
}
return propertyNames;
}
public static object GetPropertyValue(object item, PropertyInfo property)
{
var value = property.GetValue(item, null);
return value;
}
public static object GetPropertyValue(object item, string propertyName)
{
PropertyInfo property;
foreach (var part in propertyName.Split('.'))
{
if (item == null)
return null;
var type = item.GetType();
property = type.GetProperty(part);
if (property == null)
return null;
item = GetPropertyValue(item, property);
}
return item;
}
public static object GetPropertyValueDynamic(object item, string name)
{
var dictionary = (IDictionary)item;
return dictionary[name];
}
public static Dictionary GetProperties(Type type)
{
var properties = _cachedProperties.GetOrAdd(type, BuildPropertyDictionary);
return properties;
}
private static Dictionary BuildPropertyDictionary(Type type)
{
var result = new Dictionary();
var properties = type.GetProperties();
foreach (var property in properties)
{
result.Add(property.Name.ToLower(), property);
}
return result;
}
public static bool IsList(object item)
{
if (item is ICollection)
return true;
return false;
}
public static bool IsNullable(PropertyInfo property)
{
if (property.PropertyType.IsGenericType &&
property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
return true;
return false;
}
///
/// Includes a work around for getting the actual type of a Nullable type.
///
public static Type GetPropertyType(PropertyInfo property)
{
if (IsNullable(property))
return property.PropertyType.GetGenericArguments()[0];
return property.PropertyType;
}
public static object GetDefault(Type type)
{
if (type.IsValueType)
return Activator.CreateInstance(type);
return null;
}
public static bool IsBasicClrType(Type type)
{
if (type.IsEnum
|| type.IsPrimitive
|| type.IsValueType
|| type == typeof(string)
|| type == typeof(DateTime))
return true;
return false;
}
public static bool IsCustomEntity()
{
var type = typeof(T);
if (type.IsClass && Type.GetTypeCode(type) == TypeCode.Object)
return true;
return false;
}
}
#endregion
}