关于动态排序问题
本帖最后由 winamw 于 2014-02-20 23:50:45 编辑
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string orderByProperty,
bool desc) where T : class
{
//判断升序降序
string command = desc ? "OrderByDescending" : "OrderBy";
//获取t的属性
var type = typeof(T);
var property = type.GetProperty(orderByProperty);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExpression = Expression.Lambda(propertyAccess, parameter);
var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExpression));
return source.Provider.CreateQuery<T>(resultExpression);
}
通过这个方法可以自动的建立本表的查询。
会根据传来的string orderByProperty自动生成p=>p.orderByProperty
这里我传入表userinfo.表字段传什么值才可以调外键的值
比如两个表。一个是userinfo 别一个表是dep
表关系是1对多
我想他生成的是p=>p.dep.Name
------解决方案--------------------不能用Call,应该用MemberAccess
------解决方案--------------------try:
public static IQueryable OrderBy(this IQueryable source,
string ordering,
params object[] values) {
if (source == null) throw new ArgumentNullException("source");
if (ordering == null) throw new ArgumentNullException("ordering");
ParameterExpression[] parameters = new ParameterExpression[] {
Expression.Parameter(source.ElementType, "") };
ExpressionParser parser = new ExpressionParser(parameters,
ordering,
values);
IEnumerable<DynamicOrdering> orderings = parser.ParseOrdering();
Expression queryExpr = source.Expression;
string methodAsc = "OrderBy";
string methodDesc = "OrderByDescending";
foreach (DynamicOrdering o in orderings) {
queryExpr = Expression.Call(
typeof(Queryable), o.Ascending ? methodAsc : methodDesc,
new Type[] { source.ElementType, o.Selector.Type },
queryExpr, Expression.Quote(Expression.Lambda(o.Selector,
parameters)));
methodAsc = "ThenBy";
methodDesc = "ThenByDescending";
}
return source.Provider.CreateQuery(queryExpr);
}
http://stackoverflow.com/questions/2562709/iqueryablet-extension-method-not-working