Entity Framework: Dynamic Sorting


Sorting and paging on a ASP grid with Entity Framework data source


we can’t do that as simple as the following:



Lets say we have the class like the following in Entity Framework:

public Project {

int ID {get;set;}

string Name {get;set;}


We need to write our custom Expression to achieve the sorting, and let’s say we just want to order it by ascending for now.


public List<Project> GetProjects(int startRowIndex, int maximumRow, string sortParameter) {

//Default Sorting, sort by Project ID

Func<Project, object> orderExpression = p => p.ID;

switch(sortParameter) {

case “Name”:

orderExpression = p => p.Name;



using(var context = new xxxEntities()) {

//Order by sort expression, skip x number of rows, take the current page size of entities

return context.Projects.OrderBy(orderExpression).Skip(startRowIndex).Take(maximumRows).ToList();





Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s