Creating Func<IQueryable<T>, IOrderedQueryable<T>>
拡張メソッドで並べ替えのジェネリック Func を作成したい:
public static Func<IQueryable<T>, IOrderedQueryable<T>> GetOrderByFunc<T>(this KeyValuePair<string, SortingType> keyValuePair)
{
//I expect the following result
//Func<IQueryable<T>, IOrderedQueryable<T>> orderby = q => q.OrderByDescending(c => c.Name);
//keyValuePair.Key is name of property in type of T that I should sort T by it
switch (keyValuePair.Value)
{
case SortingType.Ascending:
// Creating Ascending Sorting Func
break;
case SortingType.Descending:
// Creating Descending Sorting Func
break;
default :
break;
}
}
どのようにすればよいか教えていただけますか?
編集:
この並べ替えにも、T のナビゲーション プロパティの数が含まれます。
例えば:
// keyValuePair.Key equals "User.Count"
// User is a navigation property of T
Func<IQueryable<T>, IOrderedQueryable<T>> orderby = q => q.OrderByDescending(c => c.User.Count);
編集:
以下のように変更GetSelector
しましたが、 で例外が発生しましたbodyExpression
。
public static Expression GetSelector<T>(string propertyName)
{
ParameterExpression parameter = Expression.Parameter(typeof(T));
if (propertyName.Contains("."))
{
propertyName = propertyName.Substring(0, propertyName.IndexOf("."));
Type navigationPropertyCollectionType = typeof(T).GetProperty(propertyName).PropertyType;
if (navigationPropertyCollectionType.GetGenericTypeDefinition() == typeof(ICollection<>))
{
Expression countParameter = Expression.Parameter(navigationPropertyCollectionType, "c");
MemberExpression countExpression = Expression.Property(countParameter, "Count");
//Exception: Instance property 'Users(ICollection`1)' is not defined for type 'System.Int32'
var bodyExpression = Expression.Property(countExpression, propertyName, countParameter);
return Expression.Lambda(bodyExpression, parameter);
}
}
MemberExpression bodyMemberExpression = Expression.Property(parameter, typeof(T).GetProperty(propertyName));
return Expression.Lambda(bodyMemberExpression, parameter);
}