I need to sort a query by string and found this that works well. The problem is that it can't handle complex properties related entities such as "ComplexProperty.Property""RelatedEntity.Property" since it only searches the main class.
I'm thinking I should be able to parse the parts[0] by a . and somehow recursively check each type, but I can't figure out exacly how. Is this possible or am I at a dead end?
The reason for this is that I have an "old" solution (MVC 3) with a webgrid on, and the webgrid needs all data to do the sorting (it's an detatched EF4 solution) and it just takes to much time. I need to pass the sort into the query and only retrieve the posts for that page in the paging. The webgrid calls the same controller with sort and sortdir parameters and update with ajax.
If it's not possible, maybe there is another solution that I should look at that anyoune can hint about?
Edit with clarifications Today the solution gets all violations, sends them to a webGrid and lets the webgrid do the paging and sorting. The solution has been live for many years and the violation table has grown to the point that the page is really slow, mostly becouse of that all the data is fetched every time. I have implemented paging to the repository to recieve only a portion of the class. The repository today works with IEnumerable and the ServiceLayer (business) between presentation and repository, always returns a List to presentation layer.
Here is the SQL i want to be able to use
SELECT vi.ViolationId, ar.AreaName
FROM [Violation] vi
join [ControlPoint] cp on vi.ControlPointId = cp.ControlPointId
join [Area] ar on ar.AreaId = cp.AreaId
order by ar.AreaName
I need to do this with an orderBy(string sortExpression) like this.
violations.OrderBy("ControlPoint.Area.AreaName")
and found this function (linked above) as a foundation for this.
public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> list, string sortExpression)
{
sortExpression += "";
string[] parts = sortExpression.Split(' ');
bool descending = false;
string property = "";
if (parts.Length > 0 && parts[0] != "")
{
property = parts[0];
if (parts.Length > 1)
{
descending = parts[1].ToLower().Contains("esc");
}
PropertyInfo prop = typeof(T).GetProperty(property);
// handle Prop.SubProp
// prop.GetType().GetProperty
if (prop == null)
{
throw new Exception("No property '" + property + "' in + " + typeof(T).Name + "'");
}
if (descending)
return list.OrderByDescending(x => prop.GetValue(x, null));
else
return list.OrderBy(x => prop.GetValue(x, null));
}
return list;
}