在进行数据列表的查询中,我们通常会使用两种方式进行查询:
  1. linq查询
  2. 数据库sql语句查询

这样固然可以实现查询,本人之前也都是这么做的,因为查询的条件很少。使用linq,可以将所有的查询条件的属性传到后台,再根据该属性是否有值,使用where进行查询;使用存储过程,也需要将所有查询条件的属性传到后台,

再根据该属性是否有值进行sql语句的拼接。这样做在查询条件很少的时候固然没啥影响,但是有一天做查询列表的时候,本人碰到了一个查询条件高达接近10个的情况,这样再使用上述的方法固然也可以实现,但是可能会使用多个

条件去判断,然后使用多个where查询,如果在数据库使用sql语句拼接,可能会产生很长的sql拼接查询的代码,在调试的时候还要用print去打印才能看到完整的查询条件,所以我就想,能不能写一种方法可以动态产生查询的条件

,不管列表的查询条件有十个还是几十个,我只需要将查询的属性作为一个对象传到后台,再将这个查询属性的对象丢给这个方法,让它动态产生查询的表达式,然后使用linq中的where去查询呢?于是我便踏上了探索Expression表

达式树的路途!下面我写出自己的代码,希望和大家能一起交流学习!

经过查询资料和研究,终于写出了以下这套代码来达到目的:

1.定义一个查询的特性类,_displayName用于指明查询条件的类的各个属性用于和数据源列表元素对象的各个属性比较的属性名称(注意:_displayName的值必须和数据源中各个属性名称相同),_operation用于指明比较的操作

类型,类的代码如下:

 public class SearchAttribute : Attribute
{
/// <summary>
/// 属性名称,用于对比查询
/// </summary>
private string _displayName;
/// <summary>
/// 操作类型
/// </summary>
private OperationType _operation; public string DisplayName
{
get { return _displayName; }
}
public OperationType Operation
{
get { return _operation; }
} public SearchAttribute(string displayName, OperationType operation)
{
_displayName = displayName;
_operation = operation;
} /// <summary>
/// 不是查询的条件时调用此构造函数 参数值=OperationType.None
/// </summary>
/// <param name="operation"></param>
public SearchAttribute(OperationType operation)
{
_operation = operation;
}
}
2.定义一个比较的操作类型的枚举类型
     /// <summary>
/// 查询操作类型
/// </summary>
public enum OperationType
{
/// <summary>
/// 不进行查询
/// </summary>
None,
/// <summary>
/// 比较该查询属性的值是否与元数据数据的值相等 即sql中=
/// </summary>
Equal,
/// <summary>
/// 比较元数据数据的值是否包含该查询属性的值 即sql中like
/// </summary>
Like,
/// <summary>
/// 大于
/// </summary>
GreaterThan,
/// <summary>
/// 小于
/// </summary>
LessThan,
/// <summary>
/// >=
/// </summary>
GreaterThanOrEqual,
/// <summary>
/// <=
/// </summary>
LessThanOrEqual
}
3.核心代码来了,哈哈
 public static class Query
{
public static IQueryable<TSource> Search<TSource,T>(this IQueryable<TSource> queryList, T searchOptions)
{
return queryList.Where(Search<TSource,T>(searchOptions));
} private static Expression<Func<TSource, bool>> Search<TSource,T>(T searchOptionEntity)
{
var dataSouceType = typeof(TSource); //数据源列表元素对象的类型
var dataSource = new
{
Type = dataSouceType, //数据源列表元素对象的类型
Properties = dataSouceType.GetProperties(), //数据源列表元素对象的属性集合
}; //List<string> sourcePropertyName = sourceProperties.Select(p => p.Name).ToList(); PropertyInfo[] searchProperties = searchOptionEntity.GetType().GetProperties(); //查询选择器对象的属性集合 var pe = Expression.Parameter(dataSource.Type, "p"); //创建一个 ParameterExpression 节点,该节点可用于标识表达式树中的参数或变量
var expression = Expression.Equal(Expression.Constant(true), Expression.Constant(true)); //遍历查询选择器对象的属性集合
foreach (var property in searchProperties)
{
var propertySearchAttribute = property.GetCustomAttributes(true)[] as SearchAttribute; //获取查询选择器属性的自定义特性对象
var propertySearchVlaue = property.GetValue(searchOptionEntity, null); //获取查询选择器属性的值
var propertySearchAttributeName = propertySearchAttribute.DisplayName; //获取查询选择器属性的自定义特性对象的对比查询的字段名称 //查询选择器中的该属性的自定义的对比查询的字段名称 in 数据源列表对象的属性集合 && 查询选择器中的该属性是查询的条件 && 查询选择器该属性的值!=null或者""
if (Array.Exists(dataSource.Properties, p => p.Name == propertySearchAttributeName) && propertySearchAttribute.Operation!=OperationType.None && propertySearchVlaue != null && propertySearchVlaue != (object)string.Empty)
{
var propertyReference = Expression.Property(pe, propertySearchAttributeName);
var sourcePropertyType = dataSource.Properties.FirstOrDefault(p => p.Name == propertySearchAttributeName).PropertyType; //获取数据源列表元素对象的单个属性的属性类型
ConstantExpression constantReference = null;
Expression Expr = null; bool isGenericType = sourcePropertyType.IsGenericType && sourcePropertyType.GetGenericTypeDefinition() == typeof(Nullable<>); //搜索sourcePropertyType是否可为空
if (isGenericType)
constantReference = Expression.Constant(Convert.ChangeType(propertySearchVlaue, Nullable.GetUnderlyingType(sourcePropertyType)), sourcePropertyType); //如果可为空类型,则将propertySearchVlaue的类型设置为可为空类型
else
constantReference = Expression.Constant(Convert.ChangeType(propertySearchVlaue, sourcePropertyType)); //根据查询选择器中该属性的查询条件进行不同的操作
switch (propertySearchAttribute.Operation)
{
case OperationType.Equal:
Expr = Expression.Equal(propertyReference, constantReference);
break;
case OperationType.GreaterThan:
Expr = Expression.GreaterThan(propertyReference, constantReference);
break;
case OperationType.LessThan:
Expr = Expression.LessThan(propertyReference, constantReference);
break;
case OperationType.GreaterThanOrEqual:
Expr = Expression.GreaterThanOrEqual(propertyReference, constantReference);
break;
case OperationType.LessThanOrEqual:
Expr = Expression.LessThanOrEqual(propertyReference, constantReference);
break;
case OperationType.Like:
Expr = Expression.Call(propertyReference, typeof(String).GetMethod("Contains", new Type[] { typeof(string) }), constantReference);
break;
default:break; } expression = Expression.AndAlso(expression, Expr); //最终的查询条件
}
}
return Expression.Lambda<Func<TSource, bool>>(expression, pe);
}
}
注意:必须将Query类和该类的成员方法定义为static,具体原因请搜索C#拓展方法的定义
最后,只需要在IQueryable对象上调用Search(查询条件对象)这个函数并传入参数就可以了 这是我自己定义的查询条件类
 public class ProjectInfoDTO
{
[Search("CompanyName",OperationType.Like)]
public string CompanyName { get; set; } [Search("SYS_CreateTime",OperationType.GreaterThanOrEqual)]
public DateTime? CreateTimeStart { get; set; } [Search("SYS_CreateTime", OperationType.LessThanOrEqual)]
public DateTime? CreateTimeEnd { get; set; }
}
类的属性名称不一定要与属性上面Search方法的displayName参数的值相同,但是displayName参数的值必须与查询列表对象中属性的名称相同

这是我查询的列表
 var result = (from a in db.Company_BasicInfo.Where(p => p.CompanyID > )
select new
{
a.CompanyID,
a.CompanyName,
a.SYS_CreateTime
}).Search(searchOption).OrderByDescending(p => p.SYS_CreateTime).Take().ToList();

OK,现在我不需要管我的查询条件是什么了,只需要往查询属性的对象中传入对应的值即可

 

最新文章

  1. react-native 学习之TextInput组件篇
  2. jquery 判断元素是否隐藏
  3. python 生产者消费者模型
  4. [C和指针]第三部分
  5. Win2003 Server磁盘配额揭密之补遗篇
  6. HDU 1815, POJ 2749 Building roads(2-sat)
  7. android 屏幕适配小结
  8. vue2 过渡 轮播图
  9. UE4代码片断备份
  10. 初学python之路-day04
  11. 【堆】【洛谷例题】p1090 p1334 p1177
  12. scrapy初探(一)-斗鱼TV直播信息抓取
  13. nginx配置socket服务
  14. spark基础----&gt;spark的第一个程序
  15. 修改Hosts文件提示没有权限怎么办
  16. 大数据入门第二十天——scala入门(一)入门与配置
  17. 《linux内核分析》第六周:分析fork函数对应的系统调用处理过程
  18. C#中的命名空间namespace与Java中的包package之间的区别
  19. git 添加review的相关操作
  20. tensorflow笔记之反向传播时用到的几种方法

热门文章

  1. poj 2892---Tunnel Warfare(线段树单点更新、区间合并)
  2. HibernateSessionFactory类的主要方法
  3. 第一天—ListView||内容提供者
  4. 利用Arcgis for javascript API绘制GeoJSON并同时弹出多个Popup
  5. Power BI Embedded 与 Bot Framework 结合的AI解决方案
  6. tortoiseGit保存用户名和密码
  7. 顺序线性表之大整数求和C++
  8. Android中的java层的线程暂停和恢复实现
  9. 使用express创建新应用的骨架
  10. MYSQL中 ENUM 类型的详细解释