I am attempting to use a web grid helper in conjunction with a generic repository to add column sorting. THe action result form the view with the grid helper has a parameter for the sort column (string). In my generic method signature I need to pass in a lambda expression based on the property name of the domain model (see below).
public IEnumerable<T>GetAllPagingAndSorting<TKey>(out int totalRecords,
int pageSize, int pageIndex, Expression<Func<T, TKey>> orderingKey,
SortDirection sortOrder,
params Expression<Func<T, object>>[] includes)
{}
So for example I want to map a property name of “Name” and type of “string” to m=>m.Name.
I have tries using a dictionary as in the following way but it throws an error when calling the repository method as the type is now object instead of int,string etc….
private IDictionary<string,Expression<Func<MyModel,object>>> _orderings =
new Dictionary<string, Expression<Func<MyModel,object>>>
{
{"Id",(m=>m.Id)},
{"Name",m=>m.UserName},
{"DateRequired",m=>m.DateRequired},
{"AssignedTo",m=>m.TeamMember.MemberName},
{"RequestedBy",m=>m.RequestedBy},
};
Should I use a method instead? In either case how can I use the above to match the input property and return the Lambda expression with the correct type?
Update:
Here’s my Action in the controller….thought I’d try and get the ordering key as Lambda here as I use generic repository….
Generic respoitory method defined:
IEnumerable GetAllPagingAndSorting(out int totalRecords, int pageSize, int pageIndex,Expression> orderingKey, SortDirection sortOrder, params Expression>[] includes);
public ActionResult ServerPagingAndSorting(int page = 1, string sort = "Id", string sortDir = "Ascending")
{
int totalRecords;
var viewModel =new SupportRequestsIndexVM(supportrequestRepository.GetAllPagingAndSorting(out totalRecords, PageSize,page - 1,_orderings[sort] ,GetSortDirection(sortDir),(m=>m.TeamMember)))
{PageSize = PageSize, PageNumber = page, TotalRows = totalRecords};
return View(viewModel);
}
I am now using this code to apply the sorting taken form another stack overflow q. I pass in the string to the generic repository and then call this method as follows:
Here’s my repository method: