Last active
August 29, 2015 14:16
-
-
Save jehugaleahsa/2405c3eece2fc2b0653d to your computer and use it in GitHub Desktop.
EF Orderer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Linq.Expressions; | |
using System.Reflection; | |
namespace DataModeling | |
{ | |
public class QueryOrderer<TEntity> | |
where TEntity : class | |
{ | |
private LambdaExpression defaultSortExpression; | |
private Dictionary<string, LambdaExpression> orderFieldLookup; | |
public QueryOrderer() | |
{ | |
orderFieldLookup = new Dictionary<string, LambdaExpression>(); | |
} | |
public void AddOrderMapping<TProp>(string fieldName, Expression<Func<TEntity, TProp>> selector) | |
{ | |
orderFieldLookup[fieldName] = selector; | |
} | |
public void SetDefaultSortExpression<TProp>(Expression<Func<TEntity, TProp>> selector) | |
{ | |
defaultSortExpression = selector; | |
} | |
public IQueryable<TEntity> GetOrderedEntries(string field, bool isDescending, IQueryable<TEntity> entries) | |
{ | |
return orderEntries(entries, field, isDescending); | |
} | |
private IQueryable<TEntity> orderEntries(IQueryable<TEntity> entries, string fieldName, bool isDescending) | |
{ | |
dynamic lambda = getOrderByLambda(entries, fieldName); | |
if (lambda == null) | |
{ | |
return entries; | |
} | |
if (isDescending) | |
{ | |
return Queryable.OrderByDescending(entries, lambda); | |
} | |
else | |
{ | |
return Queryable.OrderBy(entries, lambda); | |
} | |
} | |
private dynamic getOrderByLambda(IQueryable<TEntity> entries, string fieldName) | |
{ | |
if (!String.IsNullOrWhiteSpace(fieldName) && orderFieldLookup.ContainsKey(fieldName)) | |
{ | |
return orderFieldLookup[fieldName]; | |
} | |
else | |
{ | |
return defaultSortExpression; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment