これらの拡張メソッドを使用して、同様のことを実現しました。
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
属性で適切に装飾されていることを前提としています。