19 Eylül 2010 Pazar

LINQ to SQL query with dynamic OrderBy

public static class DynamicOrderBy
{

public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string orderByProperty,
bool desc) where TEntity : class
{

string command = desc ? "OrderByDescending" : "OrderBy";

var type
= typeof(TEntity);
var property
= type.GetProperty(orderByProperty);
var parameter
= System.Linq.Expressions.Expression.Parameter(type, "p");
var propertyAccess
= System.Linq.Expressions.Expression.MakeMemberAccess(parameter, property);
var orderByExpression
= System.Linq.Expressions.Expression.Lambda(propertyAccess, parameter);

var resultExpression
=
System.Linq.Expressions.Expression.Call(
typeof(Queryable), command, new Type[] { type, property.PropertyType },
source.Expression, System.Linq.Expressions.Expression.Quote(orderByExpression));

return source.Provider.CreateQuery<TEntity>(resultExpression);

}


 



reference :



http://blogs.msdn.com/b/swiss_dpe_team/archive/2008/06/05/composable-linq-to-sql-query-with-dynamic-orderby.aspx



http://stackoverflow.com/questions/307512/how-do-i-apply-orderby-on-an-iqueryable-using-a-string-column-name-within-a-gener

Hiç yorum yok:

Yorum Gönderme