Sorting multiple columns using Entity Framework Paginate

0
513
views

Entity Framework Paginate is an open-source plugin for .net applications that simplifies the dynamic sorting and filtering by storing your filter and order by expressions along with the execution condition. In the latest release of version Entity Framework Paginate 1.2.0, the feature to sort multiple columns is added. To understand how the plugin works, you can read this blog post.

Sorting multiple columns enables us to achieve the results that we get using OrderBy and ThenBy in Entity Framework. To implement multiple column sorting, you need to set the priority for each column that you are adding in the Sorts object. In the example below we are setting priority if each column and also setting the condition for LoginID sorting to be true. This means whichever column is being used for sorting, the result will be sorted by LoginID as well.

public Page<Employee> GetFilteredEmployees(int pageSize, int currentPage
                                       , string searchText, int sortBy, string jobTitle)
{
Page<Employee> employees;
var filters = new Filters<Employee>();
filters.Add(!string.IsNullOrEmpty(searchText), x => x.LoginID.Contains(searchText));
filters.Add(!string.IsNullOrEmpty(jobTitle), x => x.JobTitle.Equals(jobTitle));

var sorts = new Sorts<Employee>();

sorts.Add(sortBy == 3, x => x.JobTitle, false, 1);
sorts.Add(sortBy == 1, x => x.BusinessEntityID, true, 2);
sorts.Add(true, x => x.LoginID, true, 3);

using (var context = new AdventureWorksEntities())
{
    employees = context.Employees.Paginate(currentPage, pageSize, sorts, filters);
}

return employees;
}

By looking at the signature of the Add method on Sorts class we can see that by default every sort is in ascending order and the priority is 1. This means if the priority is not set for a sort object, and more than one column qualifies for sorting, the sorting will be performed in the sequence in which the columns were added to the Sorts object.

public void Add<TKey>(bool condition, Expression<Func<T, TKey>> expression, bool byDescending = false, int priority = 1)

You can check the full example on Github here. Let me know your experience with this feature, and feel free to suggest any enhancement.

Previous article5 Ways to take your programming skills to next level
I'm passionate about exploring the bounds of technology and its ability to create the next generation of software that can make a difference.
SHARE