/// <summary>
/// 根据不同参数动态排序
/// </summary>
/// <param name="condition">Lambda表达式</param>
/// <param name="pageIndex">当前页</param>
/// <param name="pageSize">一页条数</param>
/// <param name="total">总条数</param>
/// <param name="propertyName">需要排序的字段名</param>
/// <param name="IsDESC">是否降序</param>
/// <returns></returns>
public static List<CusClass> GetEntity(Expression<Func<Customers_tb, bool>> condition, int pageIndex, int pageSize, out int total,out string message, string propertyName, bool IsDESC)
{
MyETLockContext DbContext = new MyETLockContext();
//条件过滤
var query = DbContext.Set<Customers_tb>().Where(condition);
//创建表达式变量参数
var parameter = Expression.Parameter(typeof(Customers_tb), "cus");
//根据属性名获取属性
var property = typeof(Customers_tb).GetProperty(propertyName);
if (property!=null)
{
//创建一个访问属性的表达式
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExp = Expression.Lambda(propertyAccess, parameter);
string OrderName = IsDESC ? "OrderByDescending" : "OrderBy";
MethodCallExpression resultExp = Expression.Call(typeof(Queryable), OrderName, new Type[] { typeof(Customers_tb), property.PropertyType }, query.Expression, Expression.Quote(orderByExp));
query = query.Provider.CreateQuery<Customers_tb>(resultExp);
total = query.Count();
message = "成功";
return query.Select(s => new CusClass
{
Id = s.Id,
Name = s.Name,
AgentId = s.AgentId.HasValue ? s.AgentId.Value : 0
})
.Skip((pageIndex - 1) * pageSize)
.Take(pageSize).ToList();
}
else
{
message="字段错误";
total = 0;
return null;
}
}
EF 不同参数动态排序
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.