Entity Framework: Dynamic Sorting

Scenario:

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

Problem:  

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

Object.OrderBy(ObjectProperty)

Solution

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;

break;

}

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();

}

}

 

Advertisements