NHibernate分页获取,通用条件查询方法
解决问题:解决UI上使用NHibernate通用查询方法(仅适用于多个条件联合查询)
第一步:在UI层建立构造条件方法:
private IList<ICriterion> GetCondition(string customerName = "", string address = "")
{
Employee employee = new Employee();
List<ICriterion> queryConditions = new List<ICriterion>();
if (!string.IsNullOrEmpty(customerName))
{
queryConditions.Add(new LikeExpression("CustomerName", customerName));
}
if (!string.IsNullOrEmpty(address))
{
queryConditions.Add(new LikeExpression("Address", address));
}
return queryConditions;
}
第二步:在数据访问层使用条件集合生成NHibernate查询语句:
private IList<Employee> GetRecord(IList<ICriterion> queryConditions, int pageIndex, int pageSize, string orderField, bool isAscending)
{
ICriteria criteria = session.CreateCriteria(typeof(Employee));
foreach (ICriterion cri in queryConditions)
{
criteria.Add(cri);
}
int skipCount = (pageIndex - 1) * pageSize;
criteria.AddOrder(new Order(orderField, isAscending));
criteria.SetFirstResult(skipCount).SetMaxResults(pageSize);
return criteria.List<Employee>();
}