linq 多条件查询 where 拼接+分页

时间:2022-06-15 05:31:38

首先定义一个静态类

 public static class QueryAssembly
{
/// <summary>
/// 返回true
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static Expression<Func<T, bool>> True<T>()
{
return f => true;
} /// <summary>
/// false
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static Expression<Func<T, bool>> False<T>()
{
return f => false;
} /// <summary>
/// or
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expr1"></param>
/// <param name="expr2"></param>
/// <returns></returns>
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.Or(expr1.Body, invokedExpr), expr1.Parameters);
} /// <summary>
/// and
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expr1"></param>
/// <param name="expr2"></param>
/// <returns></returns>
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.And(expr1.Body, invokedExpr), expr1.Parameters);
}
}

定义Page类

 public class Paging<T>
{
/// <summary>
/// 当前页码
/// </summary>
[DataMember]
public int PageNo { get; set; } /// <summary>
/// 总页数
/// </summary>
[DataMember]
public int PageCount { get; set; } /// <summary>
/// 每页记录数
/// </summary>
[DataMember]
public int PageSize { get; set; } /// <summary>
/// 总记录数
/// </summary>
[DataMember]
public int RecordCount { get; set; } /// <summary>
/// 当前页的数据
/// </summary>
[DataMember]
public List<T> CurrentList { get; set; }
}

查询方法

 public Paging<DAML> QueryAJML(int pageNo, int pageSize,DAML data)
{
Paging<DAML> result = null;
Expression<Func<DAML, bool>> ExpWhere = QueryAssembly.True<DAML>();
using (IStatelessSession session = _sessionFactory.OpenStatelessSession())
{
var queryDAML = session.Query<DAML>(); if (!string.IsNullOrEmpty(data.MLH))
{
ExpWhere=ExpWhere.Or(x=>x.MLH.Contains(data.MLH));
} if (!string.IsNullOrEmpty(data.QZH))
{
ExpWhere = ExpWhere.Or(x => x.MLH.Contains(data.QZH));
} //查询
queryDAML.Where(ExpWhere); //排序
queryDAML.OrderBy(x=>x.ID); //页数
result.PageNo = pageNo;
//每页记录数
result.PageSize = pageSize;
//总记录数
result.RecordCount = queryDAML.Count();
//总页数
result.PageCount = (result.RecordCount + result.PageSize - ) / result.PageSize;
//返回数据
result.CurrentList = new List<DAML>();
result.CurrentList = queryDAML.ToList();
}
return result;
}