Expression动态查询、分页
Expression,表达式树,以lamda表达式创建,就以表达式目录树的形式将强类型的lambda表达式标识为数据结构。
排序
/// <summary>
/// 根据条件排序和查询
/// </summary>
/// <typeparam name="TKey">排序字段类型</typeparam>
/// <param name="whereLambda">查询条件 lambda表达式</param>
/// <param name="orderLambda">排序条件 lambda表达式</param>
/// <returns></returns>
public static IEnumerable<Customers> GetListBy<TKey>(Expression<Func<Customers, bool>> whereLambda, Expression<Func<Customers, TKey>> orderLambda)
{
using (NorthwindEntities db = new NorthwindEntities())
{
return db.Customers.Where(whereLambda).OrderBy(orderLambda).ToList();
}
}
常见分页
/// <summary>
/// 分页查询
/// </summary>
/// <param name="pageIndex">页码</param>
/// <param name="pageSize">页容量</param>
/// <param name="whereLambda">条件 lambda表达式</param>
/// <param name="orderBy">排序 lambda表达式</param>
/// <returns></returns>
public static List<Customers> GetPagedList<TKey>(int pageIndex, int pageSize, Expression<Func<Customers, bool>> whereLambda,
Expression<Func<Customers, TKey>> orderBy)
{
using (NorthwindEntities db = new NorthwindEntities())
{
// 分页时一定注意: Skip 之前一定要 OrderBy
return db.Customers.Where(whereLambda).OrderBy(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
}
}
调用:
var a = GetListBy<string>((p)=> p.CustomerID == "11", (q) => q.ContactName);
IQueryable<Orders> or = db.Orders.Where(u=>u.CustomerID=="11").Take(1);
List<Orders> aa = or.ToList();