我有一个扩展orderByField
public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string
SortField, bool Ascending){
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, SortField);
var exp = Expression.Lambda(prop, param);
string method = Ascending ? "OrderBy" : "OrderByDescending";
Type[] types = new Type[] { q.ElementType, exp.Body.Type };
var mce = Expression.Call(typeof(Queryable), method, types,
q.Expression, exp);
return q.Provider.CreateQuery<T>(mce);
}
我用它来传递字符串参数
string sortBy = "StatusID";
return dbContext.Requests.OrderByField(sortBy,true)
但我如何使用动态字符串参数orderBy,其中列与请求表相关,如
dbContext.Requests.OrderBy(x => x.Status.Description)
答案 0 :(得分:1)
假设您将以SortField
的形式收到"Status.Description"
参数,您会:
例如:
public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, bool Ascending)
{
var param = Expression.Parameter(typeof(T), "p");
Expression expBody = param;
string[] props = SortField.Split('.');
foreach (var prop in props)
{
expBody = Expression.Property(expBody, prop);
}
var exp = Expression.Lambda(expBody, param);
string method = Ascending ? "OrderBy" : "OrderByDescending";
Type[] types = new Type[] { q.ElementType, exp.Body.Type };
var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
return q.Provider.CreateQuery<T>(mce);
}