using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
namespace GSYWApi.Helper
{
///
/// 数据表操作类
///
///
public class OperationDataHelper
{
#region 获取通用表数据查询条件
///
/// 获取通用表数据查询条件
///
/// 实体类
/// 查询方式:0【模糊查询】,1【精确查询】
/// 查询表定义名称,如A.
/// 排除查询的字段
///
public static string GetWhereSQL(T t, int? QueryType, string OtherName = "", params string[] ExcludeName)
{
string WhereSQL = "";
var pros = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
foreach (var item in pros)
{
object value = item.GetValue(t, null);
//如果排除字段中包含当前参数,则执行下一个参数查询
if (ExcludeName != null && ExcludeName.Contains(item.Name))
{
continue;
}
//查询字符串类型参数
if (IsType(item.PropertyType, "System.String") || item.PropertyType == typeof(String))
{
if (value != null && !string.IsNullOrEmpty(value.ToString()))
{
WhereSQL += (string.IsNullOrEmpty(WhereSQL) ? "" : " AND ") + OtherName + item.Name +
(QueryType == 1 ? " = '" + value + "'" : " like '%" + value + "%'");
}
continue;
}
//查询数字类型或bool型参数
if (IsType(item.PropertyType, "System.Nullable`1[System.Int16]") ||
IsType(item.PropertyType, "System.Nullable`1[System.Int32]") ||
IsType(item.PropertyType, "System.Nullable`1[System.Int64]") ||
IsType(item.PropertyType, "System.Nullable`1[System.Double]") ||
IsType(item.PropertyType, "System.Nullable`1[System.Decimal]") ||
IsType(item.PropertyType, "System.Nullable`1[System.Boolean]") ||
item.PropertyType == typeof(Int16) || item.PropertyType == typeof(Int32) || item.PropertyType == typeof(Int64) ||
item.PropertyType == typeof(Double) || item.PropertyType == typeof(Decimal) || item.PropertyType == typeof(Boolean))
{
if (value != null)
{
WhereSQL += (string.IsNullOrEmpty(WhereSQL) ? "" : " AND ") + OtherName + item.Name + " = " + value;
}
continue;
}
//查询日期类型参数
if (IsType(item.PropertyType, "System.Nullable`1[System.DateTime]") ||
item.PropertyType == typeof(DateTime))
{
if (value != null)
{
WhereSQL += (string.IsNullOrEmpty(WhereSQL) ? "" : " AND ") + OtherName + item.Name + " = " +
string.Format("TO_DATE('{0}','YYYY/MM/DD HH24:MI:SS')", value);
}
continue;
}
}
return WhereSQL;
}
#endregion
#region 方法 -> 类型匹配
///
/// 类型匹配
///
/// 类型
/// 类型名称
///
public static bool IsType(Type type, string typeName)
{
if (type.ToString() == typeName)
return true;
if (type.ToString() == "System.Object")
return false;
return IsType(type.BaseType, typeName);
}
#endregion
}
}