0

I have a couple of classes that implement a common repository interface, one of the methods in these classes is a method that returns a Paged Result and takes a

Expression<Func<T, bool>> OrderBy

I have also created a Service Layer that will use the repository classes, as i have read it's not preferred to send an Expression object from UI To Service Layer, so i decided to send it as a parameter, if i send it as string which contains the name of the parameter how can i convert the string to be as a property to be used in an Expression Object, for example suppose i have an Entity called User and i send to the method a parameter called "UserName", how can i convert "UserName" to be turned into a "UserName" property which can be used in the Expression> OrderBy object?

if possible can you please tell me of a more suitable way to do the sorting?

  • I don't see any reason not to use the expression. – mfussenegger Jun 18 '12 at 18:55
  • the interface that you provide is more used for Where clause and not for Sorting. A sorting expression should be like: Expression> keySelector, bool asc ... – Nicolae Dascalu Jun 18 '12 at 19:18
  • I have already taken in mind the bool asc, the orderby paramter (KeySelection) is the one used for ordering, i am currently trying to use the expression class to build an orderby parameter from a string one. – Ahmad_Hamdan Jun 18 '12 at 19:32
  • The [Dynamic Linq](http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx) library does that "build orderby from string" already. Sources are also available. – mfussenegger Jun 19 '12 at 04:12

1 Answers1

0

Instead of receiving Expression<Func<T, bool>> your service could receive Func<IQueryable<T>, IQueryable<T>> which is more flexible (enables any LINQ, not just where) and doesn't require the additional work that Expressions do.

If you want to prevent misuse (e.g. code injection), then instead pass an enum (or string) (containing the sortby parameter) to the service and have your service build the query accordingly.

I hope that by UI you are not referring to the actual UI, but instead to a VM or a controller and that your views are not aware of anything below them.

Danny Varod
  • 17,324
  • 5
  • 69
  • 111
  • I will change my service layer code to accept an string or enum for the order by and through Expression class i will build the order by predicate, as for the UI yes am referring to the controller as i for the time being i will go with ASP.Net MVC – Ahmad_Hamdan Jun 19 '12 at 06:10