首先定义一个静态类
1 public static class QueryAssembly 2 { 3 /// <summary> 4 /// 返回true 5 /// </summary> 6 /// <typeparam name="T"></typeparam> 7 /// <returns></returns> 8 public static Expression<Func<T, bool>> True<T>() 9 { 10 return f => true; 11 } 12 13 /// <summary> 14 /// false 15 /// </summary> 16 /// <typeparam name="T"></typeparam> 17 /// <returns></returns> 18 public static Expression<Func<T, bool>> False<T>() 19 { 20 return f => false; 21 } 22 23 /// <summary> 24 /// or 25 /// </summary> 26 /// <typeparam name="T"></typeparam> 27 /// <param name="expr1"></param> 28 /// <param name="expr2"></param> 29 /// <returns></returns> 30 public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,Expression<Func<T, bool>> expr2) 31 { 32 var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>()); 33 return Expression.Lambda<Func<T, bool>> 34 (Expression.Or(expr1.Body, invokedExpr), expr1.Parameters); 35 } 36 37 /// <summary> 38 /// and 39 /// </summary> 40 /// <typeparam name="T"></typeparam> 41 /// <param name="expr1"></param> 42 /// <param name="expr2"></param> 43 /// <returns></returns> 44 public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,Expression<Func<T, bool>> expr2) 45 { 46 var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>()); 47 return Expression.Lambda<Func<T, bool>> 48 (Expression.And(expr1.Body, invokedExpr), expr1.Parameters); 49 } 50 }
查询方法
1 public Paging<DAML> QueryAJML(int pageNo, int pageSize,DAML data) 2 { 3 Paging<DAML> result = null; 4 Expression<Func<DAML, bool>> ExpWhere = QueryAssembly.True<DAML>(); 5 using (IStatelessSession session = _sessionFactory.OpenStatelessSession()) 6 { 7 var queryDAML = session.Query<DAML>(); 8 9 if (!string.IsNullOrEmpty(data.MLH)) 10 { 11 ExpWhere=ExpWhere.Or(x=>x.MLH.Contains(data.MLH)); 12 } 13 14 if (!string.IsNullOrEmpty(data.QZH)) 15 { 16 ExpWhere = ExpWhere.Or(x => x.MLH.Contains(data.QZH)); 17 } 18 19 //查询 20 queryDAML.Where(ExpWhere); 21 22 //排序 23 queryDAML.OrderBy(x=>x.ID); 24 25 //页数 26 result.PageNo = pageNo; 27 //每页记录数 28 result.PageSize = pageSize; 29 //总记录数 30 result.RecordCount = queryDAML.Count(); 31 //总页数 32 result.PageCount = (result.RecordCount + result.PageSize - 1) / result.PageSize; 33 //返回数据 34 result.CurrentList = new List<DAML>(); 35 result.CurrentList = queryDAML.ToList(); 36 } 37 return result; 38 }
时间: 2024-10-12 04:00:21