我已经使用这些扩展方法来实现类似的东西:
public static string GetKeyField(Type type)
{
var allProperties = type.GetProperties();
var keyProperty = allProperties.SingleOrDefault(p => p.IsDefined(typeof(KeyAttribute)));
return keyProperty != null ? keyProperty.Name : null;
}
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string orderBy)
{
return source.GetOrderByQuery(orderBy, "OrderBy");
}
public static IQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string orderBy)
{
return source.GetOrderByQuery(orderBy, "OrderByDescending");
}
private static IQueryable<T> GetOrderByQuery<T>(this IQueryable<T> source, string orderBy, string methodName)
{
var sourceType = typeof(T);
var property = sourceType.GetProperty(orderBy);
var parameterExpression = Expression.Parameter(sourceType, "x");
var getPropertyExpression = Expression.MakeMemberAccess(parameterExpression, property);
var orderByExpression = Expression.Lambda(getPropertyExpression, parameterExpression);
var resultExpression = Expression.Call(typeof(Queryable), methodName,
new[] { sourceType, property.PropertyType }, source.Expression,
orderByExpression);
return source.Provider.CreateQuery<T>(resultExpression);
}
这允许您将属性名称作为字符串传递并构建一个表达式,该表达式将其传递给常规 LINQ OrderBy() 函数。所以在你的情况下,用法是:
DbSet = Context.Set<T>();
public IQueryable<T> GetAll(int pageNumber = 0, int pageSize = 10, string sortColumn = "")
{
return DbSet.OrderBy(GetKeyField(typeof(T))).Skip(pageNumber * pageSize)Take(pageSize);
}
这假设您的实体类中的关键字段已使用该Key
属性正确修饰。